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.
Depth: It is an optional parameter which specifies the depth to flatten an array. By default, its value is 1.
It returns a newly created array containing all the sub-array elements concatenated into it.
Let's see the below examples to understand better.
A simple working of flat() method on a two dimensional array.Test it Now
Testing a multidimensional array with flat() method.Test it Now
It is clear that each element in the array is concatenated to the newly created 1D array.
Let's flatten an array upto a specified depth.Test it Now
Using flat() method with depth value as infinity.Test it Now
Let's flatten an array with holes in between.Test it Now
It is clear that all array elements are concatenated leaving the holes out, after applying the flat() method.