JavaScript Array flat() Method

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

The arr.flat() method was introduced in ES2019.

JavaScript Array flat() Method is used to flatten an array, to reduce the nesting of an array.

Syntax

arr.flat(depth)

Here, arr is an array.

Parameters: This method accepts a single parameter as mentioned above and described below:

  • depth
    • It specifies, how deep the nested array should be flattened.
    • It is an optional parameter.
    • The default value is 1 if no depth value is passed.

Return value

Returns a new array with the sub-array elements concatenated into it.

The flat() method does not change the original array.

The flat() method removes empty slots in arrays.

Examples

Below are the examples of the Array flat() method.

const arr1 = [1, [2, 3, 4], 5];
const flattened1 = arr1.flat();
console.log(flattened1); // [ 1, 2, 3, 4, 5 ]

const arr2 = [1, 2, [3, 4, [5, 6]]];

const flattened2 = arr2.flat();
console.log(flattened2); // [1, 2, 3, 4, [5, 6]]

const flattened3 = arr2.flat(2);
console.log(flattened3); //  [ 1, 2, 3, 4, 5, 6 ]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
const flattened4 = arr4.flat(Infinity);
console.log(flattened4); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

// flat() removes holes
const numArr = [1, , 3];
console.log(numArr.flat()); // [ 1, 3 ]
const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

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

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]