flat(depth = 1) returns a new array in which every element that is an array (IsArray) is replaced by its elements, recursively, up to depth levels. The default is 1, so [1, [2, [3]]].flat() is [1, 2, [3]]. flat(Infinity) flattens everything; a depth below 1 just copies. The depth goes through ToIntegerOrInfinity, so '1' works and NaN is 0.
flatMap(fn, thisArg?) calls fn(element, index, array) on each element and flattens the results exactly one level. It is equivalent to map(fn).flat(1) but builds only one array. Use it when each input produces zero, one or many outputs:
- return
[]to drop an element (a combined map and filter), - return
[a, b]to emit several, - return a non-array to emit one.
To flatten deeper, call flat after map.
Details from the spec's FlattenIntoArray:
- Only values for which
Array.isArrayis true are flattened. Array-likes,Sets, strings and typed arrays stay as single elements. - Holes in the source and in nested arrays are skipped (a
HasPropertycheck), soflatalso removes them. - The result is created with
ArraySpeciesCreate, so subclasses are preserved. - Neither mutates the original, and the copy is shallow.
Implementing flatten. An interviewer wants recursion with a depth counter (below), reduce with concat, or an iterative stack for very deep input. The recursive version is limited by call-stack depth.