Search code examples
javascriptarraysfor-loopmultidimensional-arraysub-array

Nested Arrays - updating subarrays while nesting with a for loop doesn't work?


const nestedArr = [];
// ADD CODE HERE
let arr = [];
for(let i=0; i<5; i++){
  arr.push(`loop${i}`, i);
  nestedArr.push(arr);
  // nestedArr.push([`loop${i}`, i]);
}

console.log(nestedArr)

Hey guys just wondering about some behavior of JS that I am not understanding. The challenge is solved when using the commented line in gray // nestedArr.push([loop${i}, i]); but when I try to use the other approach not commented

arr.push(`loop${i}`, i);
nestedArr.push(arr);

doesn’t work as I thought.

The approach is to first declare an array arr and push to it every 5 iterations the string loop${i} and the second element index i. Next pushing array arr into nestedArr during 5 iterations. The expected result should arr is pushed 5 times into nestedArr with each push supposedly adding one element at a time within arr. However, as you can see the pushed subarrays arr are all pushed holding 5 elements each 5 times. I was expecting the first iteration when i is 0 the subarray arr pushed to the nestedArr to be holding only one element but is holding already 5 same with other subarrays.

[['loop0', 0, 'loop1', 1, 'loop2', 2, 'loop3', 3, 'loop4', 4], ['loop0', 0, 'loop1', 1, 'loop2', 2, 'loop3', 3, 'loop4', 4], ['loop0', 0, 'loop1', 1, 'loop2', 2, 'loop3', 3, 'loop4', 4], ['loop0', 0, 'loop1', 1, 'loop2', 2, 'loop3', 3, 'loop4', 4], ['loop0', 0, 'loop1', 1, 'loop2', 2, 'loop3', 3, 'loop4', 4]]

the expected result should be

[['loop0', 0], ['loop1', 1], ['loop2', 2], ['loop3', 3], ['loop4', 4]]

With each iteration to add one element at the time within subarray arr which is pushed to nestedArr afterwards during the 5 iterations. Any idea to why?


Solution

  • You should initialize the array arr everytime the loop starts again:

    const nestedArr = [];
    for (let i = 0; i < 5; i++) {
      let arr = [];
      arr.push(`loop${i}`, i);
      nestedArr.push(arr);
    }
    console.log(nestedArr);