This article will illustrate the methods for merging or flattening an array of arrays in JavaScript.
How to Merge/Flatten an Array of Arrays in JavaScript?
To merge or flatten an array of arrays, use the following approaches:
Method 1: Merge/Flatten an Array of Arrays Using “flat()” Method
For merging or flattening an array of arrays, use the “flat()” method. It creates a new flattened array by calling itself recursively on sub-arrays. This method also takes the “depth” parameter that indicates the depth of the recursive method call. It is an optional parameter.
Example
Create an array that contains three arrays a number array, a boolean array, and a string array:
Call the flat() method with an array:
It can be seen that the arrays have been successfully merged in the single array:
Method 2: Merge/Flatten an Array of Arrays Using “concat()” Method With “apply()” Method
Use the “concat()” method with the “apply()” method for merging or flattening an array of arrays. The concat() method is utilized for merging two or more arrays in a new array. It does not modify the original array.
Example
Create an empty array named “arr”:
Invoke the concat() method with apply() method and pass the empty array and array of arrays to merge all the elements of arrays into an empty array:
Output
Method 3: Merge/Flatten an Array of Arrays Using “reduce()” Method
You can also use the “reduce()” method for merging or flattening an array of arrays. This method accepts two parameters, a callback function and an initial value that is an optional parameter. The callback function will apply to every element of an array.
Example
Call the reduce() method on the array and pass an empty array with the callback function as an argument to merge or flatten the array of arrays:
return arr.concat(val)
}, []);
It can be observed that the arrays are successfully merged into single array:
That was all about merging/flattening an array of arrays in JavaScript.
Conclusion
To merge or flatten an array of arrays, use the “flat()” method, the “concat()” method with the “apply()” method, or the “reduce()” method. All methods perform well, you can select any of these for merging or flattening arrays. This article illustrated the methods for flattening or merging an array of arrays in JavaScript.