o1n3n21
o1n3n21

Reputation: 364

Merging arrays to form array of arrays in JavaScript (ES6)

I have an arrays:

a = [1, 1, 1, 1]

Which should be merged with an array of arrays:

b = [[0],[0],[0],[0]]

To form a third:

c = [[0,1],[0,1],[0,1],[0,1]]

One way I have thought would be to run a .forEach on a and concatenate to each object of b. however, I'd like this so the list may become longer with, for example d=[2,2,2,2] creating e=[[0,1,2],[0,1,2],[0,1,2],[0,1,2]].

a = [1, 1, 1, 1];
    
b = [[0],[0],[0],[0]];

a.forEach((number,index) => {
  b[index] = b[index].concat(number)
  });
  
  console.log(b);

Thanks!

Upvotes: 1

Views: 301

Answers (2)

Bergi
Bergi

Reputation: 664548

The concat method does not append, it creates a new array that you need to something with.
You want map, not forEach - and you mixed up a and b in whose elements need to be wrapped in an array literal to be concatenated:

var a = [1, 1, 1, 1];
var b = [[0],[0],[0],[0]];

var c = a.map((number, index) => {
  return b[index].concat([number]);
});
// or the other way round:
var c = b.map((arr, index) => {
  return arr.concat([a[index]]);
});

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122047

You could use reduce() method with forEach() and create new array.

let a = [1, 1, 1, 1], b = [[0],[0],[0],[0]], d=[2,2,2,2,2]

const result = [b, a, d].reduce((r, a) => {
  a.forEach((e, i) => r[i] = (r[i] || []).concat(e))
  return r;
}, [])

console.log(result)

Upvotes: 0

Related Questions