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

← All JS array methods · TypeScript vs JavaScript