0

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

1
  • Also, post your expected output to make it clear. Commented May 12, 2020 at 4:50

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

You could assign the array to a new array and take the new value to a specified index.

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

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.