Depending on if a nested array is declared directly or with new Array(length).fill([]) I am getting strange behavior for push. If I instead use concat the code returns the expected result.
let sample = [0, 1, 2, 3];
let resultsA = [[],[],[],[]];
let resultsB = new Array(4).fill([]);
let resultsC = new Array(4).fill([]);
for (let i = 0; i < sample.length; i++) {
resultsA[i].push(sample[i]);
resultsB[i].push(sample[i]);
resultsC[i] = resultsC[i].concat(sample[i]);
}
console.log("resultsA:");
console.log(resultsA);
console.log("resultsB:");
console.log(resultsB);
console.log("resultsC:");
console.log(resultsC);
Result A: numbers are placed in correct nested array.
Result B: all nested arrays are filled with a copy of the sample array.
Result C: numbers are placed in correct nested array.
In the console all three ‘results’ arrays appear to be equivalent prior to the push / concat loop.
I know .push mutates and .concat does not, but this behavior seems to be resulting from how the target array was declared.
Why is this happening?
>Solution :
When you do this :
new Array(4).fill([]);
You are passing the same array (understand same reference) to each index of the array, so when one index is updated you will see the changes in all the index because you actually modified the array every index refers to.
So if you want to use nested arrays you shouldn’t use the fill method (and it would b ethe same problem with nested objects)