Sometimes, we want to merge or flatten an array of JavaScript arrays.
In this article, we’ll look at how to merge or flatten an array of JavaScript arrays.
Array.prototype.concat
The concat
method lets us add the items from arrays passed in as arguments into the array it’s called on.
For instance, we can write:
const arrays = [
["1"],
["2"],
["3"],
["4"],
["5"],
["6"],
];
const merged = [].concat(...arrays);
console.log(merged);
We spread the entries in arrays
to the concat
method.
The all the entries from the arrays in arrays
will be added to the empty array it’s called on and returned.
Therefore, we get [“1”, “2”, “3”, “4”, “5”, “6”]
as the result of merged
.
Array.prototype.flat
ES2019 comes with the flat
method that lets us flatten an array with any level we want.
For instance, we can write:
const arrays = [
["1"],
["2"],
["3"],
["4"],
["5"],
["6"],
];
const merged = arrays.flat(1);
console.log(merged);
Then we get the same result as before.
We pass in 1 to flat
to flatten the array one level.
If we don’t pass in an argument, then it’ll flatten recursively until there’re no more arrays left to flatten.
Write Our Own Function
Also, we can write our own function to flatten an array recursively.
For instance, we can write:
const arrays = [["1"], ["2"], ["3"], ["4"], ["5"], ["6"]];const flatten = (arr) => {
return arr.reduce((flat, toFlatten) => {
if (Array.isArray(toFlatten)) {
return flat.concat(...flatten(toFlatten));
}
return flat.concat(toFlatten);
}, []);
};
const merged = flatten(arrays);
console.log(merged);
to create the flatten
function.
We check if toFlatten
is an array in the callback of reduce
.
reduce
lets us combine items from multiple arrays into one array.
If it is, then we return the return value flat.concat
called with the flatten(toFlatten)
spread into concat
as arguments.
Otherwise, we just return the result of flat.concat(toFlatten)
since toFlatten
isn’t an array.
This means we can put it straight into the flat
array.
The 2nd argument of reduce
is the initial return value of reduce
before anything is put into it.
Conclusion
The easiest way to flatten or merge nested arrays is to use the flat
method that comes with arrays.
We can also use the concat
method to flatten one level of a nested array.
Another choice is to create our own function to flatten an array.