繁体   English   中英

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

[英]JavaScript How to replace first element of an array with each element of another array

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

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

但这仅用第二个数组的最后一个元素替换第一个元素

使用.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);

您可以将数组分配给一个新数组并将新值分配给指定的索引。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM