EDIT
I made an error. The line let tempArr = splitArr should be tempArr = car. The solutions from @Prime and @sabbir.alam are correct!
I'm working with an array called car and one of its elements (car[3]) is a string split by ", ". I've created a new array (splitArr) using .split(", ").
My goal is to create several arrays, replacing car[3] with each entry from splitArr. However, the output only contains the last value from splitArr.
I've attempted using .map .forEach and for-loop strategies. Whether placing tempArr inside or outside the loop, the results remain the same. Although the console.log inside splitArr.forEach lists each item, the final array structure doesn't change. Here's a code example.
CODE
const car = [ 'BMW', 'Serie1', 'Gray', 'Wheels, Lights, Alarm' ]; const splitArr = car[3].split(", "); const newCollection = []; splitArr.forEach(component => { console.log(component); let tempCar = [...car]; tempCar[3] = component; newCollection.push(tempCar); }); console.log(newCollection);
OUTCOME
Wheels Lights Alarm [ [ 'BMW', 'Serie1', 'Gray', 'Alarm' ], [ 'BMW', 'Serie1', 'Gray', 'Alarm' ], [ 'BMW', 'Serie1', 'Gray', 'Alarm' ] ]
DESIRED OUTCOME
Wheels Lights Alarm [ [ 'BMW', 'Serie1', 'Gray', 'Wheels' ], [ 'BMW', 'Serie1', 'Gray', 'Lights' ], [ 'BMW', 'Serie1', 'Gray', 'Alarm' ] ]
Thanks in advance!