Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are funky results happening for push depending on how target nested array was declared?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading