JavaScript Array flat() Method
The flat() method is an inbuilt array method that flattens a given array into a newly created one-dimensional array. It concatenates all the elements of the given multidimensional array, and flats upto the specified depth. We can specify the depth limit to where we need to flatten the array. By default, the depth limit is 1.
Syntax
Parameters
Depth: It is an optional parameter which specifies the depth to flatten an array. By default, its value is 1.
Return
It returns a newly created array containing all the sub-array elements concatenated into it.
JavaScript Array flat() Method Example
Let’s see the below examples to understand better.
Example1
A simple working of flat() method on a two dimensional array.
Output:
Example2
Testing a multidimensional array with flat() method.
Output:
It is clear that each element in the array is concatenated to the newly created 1D array.
Example3
Let’s flatten an array upto a specified depth.
Output:
Example4
Using flat() method with depth value as infinity.
Output:
Example5
Let’s flatten an array with holes in between.
Output:
It is clear that all array elements are concatenated leaving the holes out, after applying the flat() method.