skip to Main Content

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


  1. Chosen as BEST ANSWER

    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(() => []) or Array.from({length:3}, () => [])


  2. 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():

    ` Chrome/121
    ---------------------------------------------
    JSON.parse  1.00x | x1000  99 101 102 109 118
    Array.from  2.48x | x1000 246 256 257 259 260
    ---------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    // @benchmark Array.from
    Array.from({length: 10000}, () => []);
    
    // @benchmark JSON.parse
    JSON.parse('[' + '[],'.repeat(10000 - 1) + '[]]');
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search