在JavaScript中合并数组以形成数组数组(ES6)

时间:2022-03-29 21:14:43

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上运行.forEach并连接到b的每个对象。但是,我喜欢这个,所以列表可能会变长,例如d = [2,2,2,2]创建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!

2 个解决方案

#1


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:

concat方法不会追加,它会创建一个你需要的新数组。你想要map,而不是forEach - 你混合了a和b,其元素需要包装在一个数组文字中以便连接:

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]]);
});

#2


0  

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

您可以对forEach()使用reduce()方法并创建新数组。

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)

#1


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:

concat方法不会追加,它会创建一个你需要的新数组。你想要map,而不是forEach - 你混合了a和b,其元素需要包装在一个数组文字中以便连接:

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]]);
});

#2


0  

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

您可以对forEach()使用reduce()方法并创建新数组。

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)