6

When creating a new multidimensional array in Chrome's console like this:

var array = Array(10).fill(Array(10).fill(false));

the array looks as expected (inspect with console.table): enter image description here

But when trying to change only one cell in the array: array[5][5] = true; something strange happens: enter image description here

I have been banging my head against the wall for sometime because of this, but can't figure it out. Could this be a bug since Array.fill is an experimental/new feature?

maxjvh
  • 214
  • 1
  • 6
  • 18
  • See [Array.fill gives same object repeated. why?](https://stackoverflow.com/q/43294552/1048572) and [Undesired results when populating an array via fill vs regular array](https://stackoverflow.com/q/32349148/1048572) – Bergi Aug 31 '17 at 03:08

1 Answers1

6

It's because you actually only created two arrays. You created an inner array with 10 elements and then an outer array that has 10 elements, each of which reference the same inner array. When you change an element of the inner array and then look at the outer array, you'll see the same change in the inner array repeated 10 times.

Create your outer array with a loop instead so that a new inner array is created for every element of your outer loop.

Jason
  • 2,725
  • 2
  • 14
  • 22
  • 2
    That's it, thanks! I ended up creating the array like this: `Array(10).fill().map(_ => Array(10).fill(false))`. – maxjvh Dec 06 '15 at 14:52