Introduction

The flat() method creates a new array by flattening nested arrays within an array per the specified depth. By default, the depth is 1. Let’s look at an example,

let arr = [1, 2, [3, 4], 5];

let arr2 = arr.flat();

console.log(arr2); // [1, 2, 3, 4, 5]

This is the same as writing,

let arr = [1, 2, [3, 4], 5];

let arr2 = arr.flat(1);

console.log(arr2); // [1, 2, 3, 4, 5]
console.log(arr); // [1, 2, [3, 4], 5] → does not modify original array

Specifying depth parameter

If we have a deeply nested array and we want the array to be flattened, we can specify the level of depth. For example,

let arr = [1, 2, [[3, 4]], 5];

let arr2 = arr.flat();
console.log(arr2); // [1, 2, [3, 4], 5]

let arr3 = arr.flat(2);
console.log(arr3); // [1, 2, 3, 4, 5]

By default, the depth is 1 hence when we apply the flat() method on arr it does not flatten entirely. Since we know the depth of the nested array is 2 we can pass the parameter as 2.

If you do not know the level of depth the array contains specify the Infinity property and it will flatten recursively until a completely flattened array can be returned.

let arr = [1, 2, [[3, 4]], 5];

let arr2 = arr.flat(Infinity);
console.log(arr2); // [1, 2, 3, 4, 5]

Remove empty elements in an array using flat()

The flat() method can also remove empty elements in an array.

let arr = [1, 2, , 5];

let arr2 = arr.flat();

console.log(arr2); // [1, 2, 5]
console.log(arr); // [1, 2, empty, 5]