Merge or flatten an array of arrays in JavaScript
In this tutorial, I will saw you how to merge or flatten an array of arrays. An array of arrays basically means an array that contains multiple arrays.
These are some methods below to merge or flatten an array of arrays.
Using flat() method
The built-in JavaScript function flat()
can flatten a nested array. A nested array basically means an array within another array.
The original array is flattened and returned as a new array via the flat()
function. It flattens the array by default to a depth of 1, which only flattens one level of nesting.
const myArray = [ ["1"], ["2"], ["3"], ["4"], ["5"] ]; const flattenedArray = myArray.flat(); console.log(flattenedArray);
In the above program, I have created an array that is myArray
that contains five sub-arrays, each with a single string element.
Then, the flat()
method is called on myArray, which flattens the array by concatenating all sub-arrays into a single array.
Output:
[ '1', '2', '3', '4', '5' ]
Now, suppose we have an array that contains several nested arrays up to the level of depth 3. Then we can use the flat()
method with the parameter 2 that will flat the array till the level of depth 2.
Here is an example below:
const myArray = [ ["1"], ["2"], [["3"]], ["4"], [["5"]] ]; const flattenedArray = myArray.flat(2); console.log(flattenedArray);
In the above program, the flat()
method is called on myArray
, with a parameter value of 2, which means it will flatten the array to a depth level of 2.
Output:
[ '1', '2', '3', '4', '5' ]
Using concat() and apply() method
We can use the concat()
method to concatenate all sub-arrays into a single array, and the apply()
method to pass the sub-arrays as individual arguments to the concat()
method.
const myArray = [ ["1"], ["2"], ["3"], ["4"], ["5"] ]; var result = [].concat.apply([], myArray); console.log(result);
In the above program, the concat()
method is used to merge two or more arrays, to concatenate all the arrays in myArray
into a single array.
Then, the apply()
method is used to pass myArray as an array-like object argument to the concat()
method.
The contact()
method concatenates all the arrays in myArray
and returns a new array that contains all the elements of the concatenated arrays.
Then, the final result is assigned to the result
variable and printed to the console using the console.log()
method.
Output:
[ '1', '2', '3', '4', '5' ]
Leave a Reply