JavaScript Array flat()

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

Example


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

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

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:

Output

[ 1, 3 ]

Recommended Reading: JavaScript Array flatMap()