Javascript: Merge array of arrays to flat array

This tutorial will guide to flatten or merge array of arrays to flat array in JavaScript language.

Javascript: Merge array of arrays to flat array

There are many ways using which you can merge array of arrays in JavaScript. Let’s learn each approach with an example.

Merge array of arrays to flat array

using concat

You can use apply() method of concat and pass the given array of arrays as a second parameter to the apply method as shown in the example below.

Let’s say myarrays is the given array of arrays and you need to convert it to a flat array.

var myarrays = [
  ["10"],
  ["11"],
  ["22"],
  ["25"],
  ["13"],
  ["16"],
  ["30"],
  ["34"],
  ["40"]
];

Below is the code used to flatten arrays using concat.apply() method.

var flattenArray = [].concat.apply([], myarrays);
console.log(flattenArray)

(9) ["10", "11", "22", "25", "13", "16", "30", "34", "40"]
0: "10"
1: "11"
2: "22"
3: "25"
4: "13"
5: "16"
6: "30"
7: "34"
8: "40"
length: 9
__proto__: Array(0)

using Array.prototype.flat()

The Array.prototype.flat() method can create a new array with all the sub-array elements concatenated into it recursively up to the specified depth.

Syntax:

flat()
flat(depth)

Note, depth is optional. The depth level is used to specify how deep the nested array structure should be flatted. And it defaults to value 1.

For example,

> const flattenArray2 = myarrays.flat(1); 

> console.log(flattenArray2)

> (9) ["10", "11", "22", "25", "13", "16", "30", "34", "40"]
0: "10"
1: "11"
2: "22"
3: "25"
4: "13"
5: "16"
6: "30"
7: "34"
8: "40"
length: 9
__proto__: Array(0)

using JavaScript reduce() function

The below solution uses JavaScript reduce function.

myarrays = myarrays.reduce(function(a, b){
     return a.concat(b);
}, []);

Output

["10", "11", "22", "25", "13", "16", "30", "34", "40"]

The above JavaScript reduce function can also be well written in one line as per ES2015 as shown below. And you would get the expected output.

myarrays = myarrays.reduce((a, b) => a.concat(b), []);

Output

["10", "11", "22", "25", "13", "16", "30", "34", "40"]

using ECMAScript 6 function

This is another function style ECMAScript 6 solution to flatten arrays in JavaScript.

const flattenArrays = arrays => arrays.reduce(
  (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []
);

Output

flattenArrays(myarrays)
["10", "11", "22", "25", "13", "16", "30", "34", "40"]

using join() and split() method

You can also use join() and split() method as shown below to convert array of arrays to flat array in JavaScript.

myarrays.join(',').split(',');
["10", "11", "22", "25", "13", "16", "30", "34", "40"]

That’s it. You had learnt numerous ways to merge array of arrays to flat array in JavaScript.

Hope it is helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments