javascript tutorial - [Solved-5 Solutions] Merge/flatten an array of arrays in javascript - javascript - java script - javascript array



Problem:

We have a JavaScript array like:

[["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]
click below button to copy the code. By JavaScript tutorial team

How would we go about making this just:

["$6", "$12", "$25", ...]
click below button to copy the code. By JavaScript tutorial team

Solution 1:

We can use concat to merge arrays:

var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
var merged = [].concat.apply([], arrays);
click below button to copy the code. By JavaScript tutorial team

Using the apply method of concat will just take the second parameter as an array, so the last line is identical to this:

var merged2 = [].concat(["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]);
click below button to copy the code. By JavaScript tutorial team

Solution 2:

Here's a short function that uses some of the newer JavaScript array methods to flatten an n-dimensional array.

function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}
click below button to copy the code. By JavaScript tutorial team

Usage:

flatten([[1, 2, 3], [4, 5]]); // [1, 2, 3, 4, 5]
flatten([[[1, [1.1]], 2, 3], [4, 5]]); // [1, 1.1, 2, 3, 4, 5]

click below button to copy the code. By JavaScript tutorial team

Solution 3:

Here's a simple and performant functional solution:

var result = [].concat.apply([], [[1],[2,3],[4]]);
console.log(result); // [ 1, 2, 3, 4 ]

click below button to copy the code. By JavaScript tutorial team

Solution 4:

It can be best done by javascript reduce function.

var arrays = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"], ["$0"], ["$15"],["$3"], ["$75"], ["$5"], ["$100"], ["$7"], ["$3"], ["$75"], ["$5"]];

arrays = arrays.reduce(function(a, b){
     return a.concat(b);
}, []);
click below button to copy the code. By JavaScript tutorial team

Or, with ES2015:

arrays = arrays.reduce((a, b) => a.concat(b), []);
click below button to copy the code. By JavaScript tutorial team

Solution 5:

We can use Underscore :

var x = [[1], [2], [3, 4]];

_.flatten(x); // => [1, 2, 3, 4]
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Merge/flatten an array of arrays in javascript