简体   繁体   中英

Merge N arrays containing arrays in javascript

I have an array which contains arrays too. this array is template 在此处输入图片说明

template has 2 arrays, but 2 is not fixed, it can go on N number of arrays which also contains arrays. this is what I tried:

const template = health_pack_templates.map((healthpackItem, i) => {
  return healthpackItem.health_pack_templates
});
console.log('template', template);
var c = [];
  for (var i = 0; i >= template.length; i++) {
      c.push.apply(template[i]);
  }
console.log('c',c)

c does only returns [] and not an array with 0,1,2,3,4,5,6,7,8,9 arrays inside. What am I doing wrong?

what I want to happen should be like this: [array 0,1,2,3,4,5,6,7,8,9] after it is merged.

Try using flat() method

The flat() method which creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Maybe because you wrote i>=template.length. it should brake your for loop immediately.

Merge N Arrays

There are multiple ways in javascript today to merge variable number of arrays

Option 1 is to use reduce:

let arrs = [[1, 2], [3, 4], [5, 6]];
arrs.reduce((a, b) => [...a, ...b], []);

This is a slow solution (quadratic time).

Option 2 is that you can use Lodash:

_.flatten

This merges n arrays, and does it more efficiently (linear time).

Option 3 is to use concat function on array of arrays:

[].concat(...arrs);

Which should be efficient (linear time).

Option 4 is to use .flat()

[...arrs].flat()

If there are more than 1 level of nested arrays you might need to use [...arrs].flat(2) and so on

let arrs = [[1, 2], [3, [7, 8], 4], [5, 6]];
[...arrs].flat(2)

There are many solution for this.

I adveced you:

var a = [1, 2, 3];
var b = [3, 4, 5];

var c = [...a, ...b];

Which result is [1, 2, 3, 4, 5, 6];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM