4

I have an array which contains arrays too. this array is template enter image description here

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.

1
  • 2
    What does apply do? Commented Mar 26, 2019 at 7:20

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@eibersji welcome!. Also, check alternatives here
3

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.