patternjavascriptCritical
Merge/flatten an array of arrays
Viewed 0 times
arrayarraysmergeflatten
Problem
I have a JavaScript array like:
How would I go about merging the separate inner arrays into one like:
[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]How would I go about merging the separate inner arrays into one like:
["$6", "$12", "$25", ...]Solution
ES2019
ES2019 introduced the
Older browsers
For older browsers, you can use
Using the
ES2019 introduced the
Array.prototype.flat() method which you could use to flatten the arrays. It is compatible with most environments, although it is only available in Node.js starting with version 11, and not at all in Internet Explorer.const arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
const merge3 = arrays.flat(1); //The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
console.log(merge3);
Older browsers
For older browsers, you can use
Array.prototype.concat to merge arrays:var arrays = [
["$6"],
["$12"],
["$25"],
["$25"],
["$18"],
["$22"],
["$10"]
];
var merged = [].concat.apply([], arrays);
console.log(merged);
Using the
apply method of concat will just take the second parameter as an array, so the last line is identical to this:var merged = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);Code Snippets
var merged = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);Context
Stack Overflow Q#10865025, score: 2611
Revisions (0)
No revisions yet.