JavaScriptArrays
Array. prototype. flat()
Flattens nested arrays down to the given depth.
- Returns
- A new, flattened array.
- Changes the original
- No
Example
#JavaScript
const nested = [1, [2, 3], [4, [5, [6]]]]
console.log(nested.flat())
console.log(nested.flat(2))
console.log(nested.flat(Infinity))Console
[1, 2, 3, 4, [5, [6]]]
[1, 2, 3, 4, 5, [6]]
[1, 2, 3, 4, 5, 6]
Definition and usage
#The flat() method creates a new array in which nested arrays are unpacked into individual elements. By default it flattens one level of nesting.
The argument sets the depth: flat(2) flattens two levels, and flat(Infinity) flattens all of them, no matter how deep.
Along the way it also removes holes in sparse arrays. The original array doesn’t change.
Syntax
#Syntax
array.flat()
array.flat(depth)Parameters
#depth
optional
The number of levels to flatten. Defaults to 1.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- If you map first and then flatten, use
flatMap()instead ofmap().flat(). flat(Infinity)is convenient, but on unknown, very deep data it can get expensive.
Related entries
#Spotted a mistake or missing an example? Write to us.