Array in loop

Hi Colleagues!
I have this piece of code:

let dump1 = [];
let arrInput = [1];

for (let i = 0; i < 3; i++) { 
  arrInput.push(1);
  dump1[i] = arrInput;
}
console.log(dump1);

I expect to get this:

[ [ 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1, 1 ] ]

But I get

[ [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ], [ 1, 1, 1, 1 ] ]

What is wrong?
Why is the value of every key of dump1 overwrited as [ 1, 1, 1, 1 ] ?

then you would need to create new arrays, arrInput is just one array.

Shouldn’t it be:

let dump1 = [];
let arrInput = [1];

for (let i = 0; i < 3; i++) { 
  arrInput.push(1); // adds another value to the array of arrInput
  dump1.push(arrInput); // pushes the array of arrInput to the dump1 everytime it iterates.
}
console.log(dump1);

Hmm testing it but I am getting the same result as the ts noted. Weird.

no, it makes sense?

arrInput is a list in memory, each time you push into dump1, arrInput pointer will still point to the same list in memory, so when changes are made, all pointers to arrInput array will show the changes.

that is why you need to make new arrays

I found the decision:

let dump1 = [];
let arrInput = [1];

for (let i = 0; i < 3; i++) { 

  arrInput.push(1);
  dump1[i] = arrInput.slice();
  
}
console.log(dump1);

slice() makes a independent copy of arrInput.

1 Like

slice will make a new array, that will work.

2 Likes