0

I was trying to push a new value to a nested array in javascript but something went wrong.

let bucket = new Array(10).fill([]);
bucket[0]= [1,2]
bucket[1].push(3);
console.log(bucket);

and then I got this result

[
    [
        1,
        2
    ],
    [
        3
    ],
    [
        3
    ],
    [
        3
    ],
    [
        3
    ],
    [
        3
    ],
    [
        3
    ],
    [
        3
    ],
    [
        3
    ],
    [
        3
    ]
]

I don't get it. Why did it push to all the empty nested arrays, is there some documentation for this? And how can I push a value to a nested value otherwise?

Howard Do
  • 33
  • 6
  • this is not a duplicate, I wasn't trying to add the value multiple times with those nested arrays but rather adding only once at an empty nested array. But the result is not what I expected, multiple arrays were added. – Howard Do Jul 12 '21 at 16:19
  • `new Array(10).fill([]);` creates an array that's filled with the same reference to `[]`. `bucket[0]= [1,2]` overwrites the reference. `bucket[1].push(3);` changes the referenced object. In JavaScript every non-primitive is a reference: https://jsfiddle.net/vmk108zw/1/ –  Jul 13 '21 at 07:49
  • That's the second sentence in the accepted answer in the duplicate: _"For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array."_ –  Jul 13 '21 at 08:02

0 Answers0