Array.prototype.flat()
Returns a new array with sub-array elements flattened to the specified depth.
Syntax
arr.flat(depth) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
depth | number | No | How many levels of nesting to flatten. Defaults to 1. Use Infinity to flatten fully. |
Returns
Array — A new flattened array.
Examples
console.log([1, [2, [3]]].flat());
Output
[ 1, 2, [ 3 ] ]
console.log([1, [2, [3, [4]]]].flat(Infinity));
Output
[ 1, 2, 3, 4 ]
Notes
Does not mutate the original array. Also removes empty slots in sparse arrays.
For mapping then flattening one level, `flatMap` is more efficient.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 69 |
| firefox | 62 |
| safari | 12 |
| edge | 79 |
| node | 11 |