JavaScript如何用另一个数组的每个元素替换数组的第一个元素

问题描述 投票:0回答:2

我有两个数组,我需要用第二个数组的每个元素替换第一个数组的第一个元素:

let firstArray = [
  [1, 'a', 'hello'],
  [2, 'b', 'world'],
  [3, 'c', 'other'],
  ...
];

let secondArray = [1, 3, 7, ...];

// Result: 
// [
//  [1, 'a', 'hello'],
//  [3, 'b', 'world'],
//  [7, 'c', 'other'],
//  ...
// ] 

我尝试做这样的事情:

firstArray.map(f => {
  secondArray.forEach(s => {
      f.splice(0, 1, s);
  })
})

但是此仅将第一个元素替换为第二个数组的最后一个元素

javascript arrays splice
2个回答
1
投票

使用.map将一个数组转换为另一个数组:

const firstArray = [
  [1, 'a', 'hello'],
  [2, 'b', 'world'],
  [3, 'c', 'other'],
];

const secondArray = [1, 3, 7];

const transformed = firstArray.map(([, ...rest], i) => [secondArray[i], ...rest]);
console.log(transformed);

另一个选项:

const firstArray = [
  [1, 'a', 'hello'],
  [2, 'b', 'world'],
  [3, 'c', 'other'],
];

const secondArray = [1, 3, 7];

const transformed = firstArray.map((item, i) => [secondArray[i]].concat(item.slice(1)));
console.log(transformed);

0
投票

您可以将数组分配给新数组,并将新值带入指定的索引。

const
    firstArray = [[1, 'a', 'hello'], [2, 'b', 'world'], [3, 'c', 'other']],
    secondArray = [1, 3, 7],
    result = firstArray.map((a, i) => Object.assign([], a, { 0: secondArray[i] }));

console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.