JavaScript Array flat() MethodThe 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. SyntaxParametersDepth: It is an optional parameter which specifies the depth to flatten an array. By default, its value is 1. ReturnIt returns a newly created array containing all the sub-array elements concatenated into it. JavaScript Array flat() Method ExampleLet's see the below examples to understand better. Example1 A simple working of flat() method on a two dimensional array. Test it NowOutput: Example2 Testing a multidimensional array with flat() method. Test it NowOutput: 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. Test it NowOutput: Example4 Using flat() method with depth value as infinity. Test it NowOutput: Example5 Let's flatten an array with holes in between. Test it NowOutput: It is clear that all array elements are concatenated leaving the holes out, after applying the flat() method.
Next TopicJavaScript Array
|