Array.prototype.flat()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
The flat() method of Array instances creates a new array with all sub-array
elements concatenated into it recursively up to the specified depth.
Try it
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]
const arr2 = [0, 1, [2, [3, [4, 5]]]];
console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]
console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]
console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]
Syntax
flat()
flat(depth)
Parameters
depthOptional-
The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
Return value
A new array with the sub-array elements concatenated into it.
Description
The flat() method is a copying method. It does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array.
The flat() method removes empty slots if the array being flattened is sparse. For example, if depth is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves.
The flat() method is generic. It only expects the this value to have a