#41: arr.flat() vs arr.flat(Infinity)
Topic: arrays · Difficulty: ★
const arr = [1, [2, [3, [4]]]];
console.log(arr.flat());
console.log(arr.flat(Infinity));Output
[ 1, 2, [ 3, [ 4 ] ] ] [ 1, 2, 3, 4 ]
Why
Array.prototype.flat() takes an optional depth argument that defaults to 1 — it only flattens one level of nesting, so a triple-nested array like [1, [2, [3, [4]]]] only has its outermost array merged in, leaving [3, [4]] still nested one level deep inside. Passing Infinity as the depth tells flat() to keep flattening recursively until there is no nesting left at all, producing a fully flat [1, 2, 3, 4]. Forgetting the default depth of 1 is a common surprise when flattening deeply nested data.