I want to push an item at a given index of an empty 2D array, but for some reason, the item gets pushed into ALL the indices.
If I explicitly create the array, it works fine:
const arr = [[], [], []]
arr[1].push('a')
console.log(arr)
// [[], ['a'], []]
However, if I use new Array, it’s as though the reference to each index is shared and it gets added to ALL indices as stated earlier:
const arr = new Array(3).fill([])
arr[1].push('a')
console.log(arr)
// [['a'], ['a'], ['a']]
Why is this happening? If it’s unavoidable, what’s the best way to instantiate a 2D array in a clean manor, as with the second example AND be able to push elements to a single index?
2
Answers
Looks like it WAS using the same reference to create all the indices of the 2D array.
To solve this use
new Array(3).fill().map(() => [])
orArray.from({length:3}, () => [])
As mentioned you should fill the array with unique objects, use the map callback in
Array.from()
for example.But if you fill a huge array you could consider
JSON.parse()
: