transformation
Array.prototype.flat
Returns a new array with all sub-array elements concatenated up to the specified depth (ES2019). Reach for it to unnest arrays of arrays without a manual reduce.
arr.flat(depth = 1) Parameters
| Parameter | Purpose |
|---|---|
| depth | How deep to flatten; defaults to 1. Use Infinity to fully flatten |
| return value | A new array (non-mutating); empty slots are removed |
Examples
console.log([1,[2,3],[4,[5]]].flat()); Logs: [1, 2, 3, 4, [5]] (depth 1 by default)
console.log([1,[2,[3,[4]]]].flat(Infinity)); Logs: [1, 2, 3, 4]
console.log([1, , 3, [4, , 5]].flat()); Logs: [1, 3, 4, 5] (also drops holes)
console.log([[1,2],[3,4]].flat(0)); Logs: [[1, 2], [3, 4]] (depth 0 clones without flattening)
Gotcha
Default depth is 1, not Infinity — pass Infinity to fully flatten deeply nested data. flat also removes empty slots.
Related methods
Array.prototype.flatMap
Maps each element with a callback, then flattens the result by one level (ES2019). Reach for it when a mapper naturally returns arrays and you want a single flat list back.
Array.prototype.concat
Returns a new array formed by joining the source with the provided arrays and/or values (one level of spread). Reach for it to merge arrays without mutating any of them.
Array.prototype.reduce
Runs a reducer function on each element, left-to-right, folding the array into a single accumulated value. Reach for it to sum/product/group/build an object or any custom fold.
Array.prototype.sort
Sorts the array in place and returns the same array; without a compareFn elements are coerced to strings and sorted lexicographically. Reach for it when you need ordered data — but always pass a compareFn for numbers.
Array.prototype.reverse
Reverses the order of elements in place and returns the same (mutated) array. Reach for it when you truly want to reverse the source; otherwise use toReversed().