JavaScript Array flat() method
creates a new array with all sub-array elements concatenated into it recursively up to the specified depth

flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

syntax

flat(depth)

depth (optional). The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.

flat() (no parameter) returns an array 1 depth level flatter than the original array.

flat(depth) returns an array the specified depth level flatter than the original array.

flat() method does not change the original array.

myArray.flat() is equal to myArray.flat(1)

If you set depth level to Infinity, all levels will be flattened.

const myArray1 = [1, 2, [3, [4, [5, 6]], 7], 8, 9, 0];

myArray1.flat(Infinity); returns ↴

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

flat() method will remove the holes if an array has empty slots.

const myArray2 = [0,, 1, 2,, [3, 4]];

myArray2.flat(); returns ↴

[0, 1, 2, 3, 4]

syntax 1 description
create a new array by flattening a nested array (myArray) 1 depth level flatter than original array
myArray.flat()
syntax 2 description
create a new array by flattening a nested array (myArray) the specified depth levels flatter than original array
myArray.flat(depth)