Skip to content
Advertisement

Change Array[3] for every item in other array

EDIT Made a mistake in my question. The let tempArr = splitArr is wrong. This needs to be: tempArr = car. So the awnser of @Prime and @sabbir.alam does the trick!


I have a array of values where one value (car[3]) of the array is a string seperated by “, “. I created a new array of those elements (splitArr) with the .split(“, “).

Now i want to create n number of arrays and replace car[3] with a item in splitArr. But my outcome is only with the last value of the splitArr.

I tried .map .forEach for-loop. The tempArr inside and outside the .arryafunction or for-loop. But always the same result, while the console.log inside the splitArr.forEach shows every item of the splitArr. Below some visual guidence.

CODE

const car = [ 
  'BMW',
  'Serie1',
  'Gray',
  'Wheels, Lights, Alarm' ]

const splitArr = car[3].split(", ");
const newArr = [];

splitArr.forEach(item => {
  console.log(item);
  let tempArr = splitArr; // This needs to be: car!
  tempArr[3] = item;
  newArr.push(tempArr);
});

console.log(newArr);

OUTCOME

Wheels
Lights
Alarm
[
  [ 'Wheels', 'Lights', 'Alarm', 'Alarm' ],
  [ 'Wheels', 'Lights', 'Alarm', 'Alarm' ],
  [ 'Wheels', 'Lights', 'Alarm', 'Alarm' ]
]

WANTED OUTCOME

Wheels
Lights
Alarm
[
  [ 'BMW', 'Serie1', 'Gray', 'Wheels' ],
  [ 'BMW', 'Serie1', 'Gray', 'Lights' ],
  [ 'BMW', 'Serie1', 'Gray', 'Alarm' ]
]

Thanks in advance!

Advertisement

Answer

The main reason that your code doesn’t work is that you don’t understand the correct way to clone array in JavaScript. You can get more details here. https://www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array/

const car = [ 
    'BMW',
    'Serie1',
    'Gray',
    'Wheels, Lights, Alarm' ]
  
  const splitArr = car[3].split(", ");
  const newArr = [];
  
  splitArr.forEach(item => {
    console.log(item);
    let tempArr = [...splitArr]; // <----------------------------------
    tempArr[3] = item;
    newArr.push(tempArr);
  });
  
  console.log(newArr);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement