0

I create a two-dimensional array like this:

array = new Array(3).fill([])

result is array like this [[], [], []]

Now I want to add element to have array like this [['new'], [], []].
I thought that array[0].push('new') will do this, but instead it's result is: [['new'], ['new'], ['new']]

Can someone explain me why?

Marcin Doliwa
  • 3,639
  • 3
  • 37
  • 62
  • 2
    Using `fill()` this way fills the array with references to a single array, not multiple arrays. From the [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#description): *'If the first parameter is an object, each slot in the array will reference that object.'* – pilchard May 22 '22 at 20:51
  • 1
    Also: [Modifying one index of multidementional array causes every other child array to mutate?](https://stackoverflow.com/questions/64381748/modifying-one-index-of-multidementional-array-causes-every-other-child-array-to) See: [How can I create a two dimensional array in JavaScript?](https://stackoverflow.com/questions/966225/how-can-i-create-a-two-dimensional-array-in-javascript) for options to avoid this. – pilchard May 22 '22 at 20:55
  • Thanks, @pilchard, it's all clear now. I initialized it with the loop and it works. Thanks. – Marcin Doliwa May 22 '22 at 21:01

0 Answers0