1

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!

0

2 Answers 2

3

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]]);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Have you tried it as a[index] rather than [a[index]]?
@Matt concat works with non-array values (like the a integers) as well, but I find that confusing when arguing about types.
0

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)

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.