Search code examples
javascriptarrayssplice

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


I have two arrays and I need to replace the first element of the first array with each elements of the second array:

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'],
//  ...
// ] 

I tried doing something like this:

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

But this replace the first element only with the last element of second array


Solution

  • Use .map to transform an array into another:

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

    Another option:

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