JavaScript Array flat()

The flat() method creates a new array by flattening a nested array up to the specified depth.

Example

// 3 nested arrays 
let numbers = [1, 2, [3, 4, [5, 6, [7, 8]]]];

// reducing nesting by flattening the array to depth 2 let flattenArray = numbers.flat(2);
// new flatten array console.log(flattenArray); // Output: // [ 1, 2, 3, 4, 5, 6, [ 7, 8 ] ]

flat() Syntax

The syntax of the flat() method is:

arr.flat(depth)

Here, arr is an array.


flat() Parameters

The flat() method takes a single parameter:

  • depth - Integer specifying how deep a nested array should be flattened. Its default value is 1.

flat() Return Value

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

Notes: The flat() method:

  • does not change the original array.
  • removes empty slots in arrays.

Example 1: Using flat() Method

// 3 nested array 
let numbers = [1, 2, [3, 4, [5, 6, [7, 8]]]];

// reducing nesting by flattening the array to depth 2 let flattenArray = numbers.flat(2);
// new flatten array console.log(flattenArray);

Output

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

In the above example, we have used the flat() method to flat the nested array numbers to depth 2.

numbers.flat(2) reduces the nesting of the numbers array and returns a flatted array with only one nesting i.e. [ 1, 2, 3, 4, 5, 6, [ 7, 8 ] ]


Example 2: flat() Without Default Depth Argument

// nested array
let array1 = [1, [2, 3, 4], 5];

// without passing any depth argument in flat() let flattenArray = array1.flat();
console.log(flattenArray);

Output

[ 1, 2, 3, 4, 5 ]

Here, we have not passed any depth argument in the flat() method.

The default depth argument is 1, so array1.flat() flattens array1 to depth 1.


Example 3: flat() to Remove Holes in Array

We can remove holes in an array that has empty slots using the flat() method. For example:

// array with empty slots
let array_with_holes = [1, , 3];

// removes holes in the array let flattedArray = array_with_holes.flat();
console.log(flattedArray); // [ 1, 3 ]

Output

[ 1, 3 ]

Also Read:

Did you find this article helpful?