Array.prototype.flat
Flattens nested arrays into one.
Available since: ES2019
Syntax
array.flat(depth)Parameters
| Parameter | Type | Description |
|---|---|---|
| depth | number | Optional. How many levels of nesting to unpack. 1 by default. |
Return value
ArrayA new flattened array.
Examples
One level of nesting:
console.log([[1, 2], [3, 4]].flat().join(', '));Output:
1, 2, 3, 4Deep nesting — depth or Infinity:
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat().length);
console.log(nested.flat(Infinity).join(', '));Output:
3
1, 2, 3, 4Notes
Empty slots (like in [1, , 3]) are removed. The original array is not changed.
See also
- Array.prototype.flatMap — Maps each element with a function and flattens the result one level.
- Array.prototype.concat — Merges arrays into a new array.
Related recipes
In the tutorial
- Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.