0

I generate a 3x3 grid

const grid = Array(3).fill(Array(3).fill(0))
[[0,0,0],
 [0,0,0],
 [0,0,0]]

I set the value of the middle cell to 1

grid[1][1] = 1

I expect to see

[[0,0,0],
 [0,1,0],
 [0,0,0]]

but instead see

[[0,1,0]
 [0,1,0],
 [0,1,0]]

It seems that all rows are referring to the same array in memory. A console.log(grid) shows

[[0, 1, 0],
 [circular object Array],
 [circular object Array]]

What exactly is going on? How can I properly generate a matrix where each cell is independent?

pinkboid
  • 51
  • 5

1 Answers1

0

Array(3).fill(0) creates a new array. But it creates only one array. Now you are filling the outer Array(3).fill with the same array three times. The reference is same for all grid[x] where x lies from 0 to 2.

Here is the relevant doc.

If value is the value to be filled using Array.fill(value):

Note all elements in the array will be this exact value: if value is an object, each slot in the array will reference that object.

You are better off using a loop:

const grid = [];

for(let i =0 ; i < 3; i++){
grid.push(Array(3).fill(0));
}
grid[1][1]=1;
console.log(grid);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39