Let us consider a 2-dimensional nested array as shown below.
An array is called a nested array when there are arrays inside this array as its elements.
The above array, arr, when flattened would look like:
Table of Contents
Different methods to flatten an array
a. Using concat() and apply()
Here we use 2 methods. concat() and apply(). We pass 2 arguments to the apply method. An empty array and the array we declared above(arr) then concatenate all the elements(sub-arrays) passed into an empty array thus obtaining a 1-dimensional array.
b. Using the spread operator
Here when we use the spread operator on the array arr we declared above, the Spread syntax (...) allows the concatenation operation to be performed on all the elements of the array and stores the result in an empty array thus giving us a flattened array.
c. Using the reduce method
The reduce() method executes a reducer function (a function that you provide as an argument) on each element of the array, resulting in a single output value. Here, the reducer function provided is concat() and the result is stored in an empty array.
2. Obtaining a flattened array by specifying the depthThe depth of an array is the number of levels of bracket pairs in the array. Specifying the depth gives us the flexibility to flatten an array to the level we want to
a. Using the flat() methodThe flat() method is used to create a new array with all sub-array elements concatenated into it recursively up to the specified depth. The depth parameter is optional and when no depth is specified, a depth of 1 is considered by default
Let us consider another array, this time of dimension greater than 2
Using the flat method on this array without specifying the depth gives the following output
As expected, the dimension of the arr1 has been reduced only by 1 since that is the default value when no depth parameter is specified.
Now, if we specify a depth of 2, the array is completely flattened reducing its dimension by 2
flat() method also deals with array holes(i.e. empty array elements) while flattening an array as shown below
Browser SupportThe array flat() method works with all modern browsers except for the Internet Explorer. Mentioned below are the oldest versions of the most common browsers that fully support the flat() method
- Chrome: 69
- Edge: 79
- Firefox: 62
- Opera: 56
- Safari: 12