Change Array[3] for every item in other array

Viewed 54

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!

4 Answers

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

That's because you keep adding the same array (splitArr) and modifying it. You need to make a deep copy every time instead:

  ...
  let tempArr = JSON.parse(JSON.stringify(splitArr));
  tempArr.push(item);
  ...

Note that using push is safer in the sense that you will notice if you are making the above mistake, because the array will keep growing rather than being changed.

Using map() would be a good strategy. For each iteration return the array that is looped over with the current item in a new array.

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

const splitArr = car[3].split(", ");
const result = splitArr.map((item, i, arr) => [...arr, item]);

console.log(result);

You should create the temp array like this let tempArr = [...splitArr]. When you directly assign the splitArray you are referencing the same array. So any update on tempArray reflects on splitArray.

Related