2

I was doing some DFS stuff and wanted to use array that was the same size as the original matrix to toggle whether nodes were visited. I noticed when I tried to set the node as visited visited[r][c] = true, it ended up setting the entire column. I realized this only happens with Array(numberOfRows).fill(Array(numberOfCols).fill(false)).

Was wondering why it does that, and if there's a better way to initialize a 2D array with a set number of rows/cols?

var foo = [
  [false,false],
  [false,false],
];
foo[0][0] = true;

var bar = Array(2).fill(Array(2).fill(false));
bar[0][0] = true;

console.log(foo);  // [[ true,false],[false,false]] (what I expected)
console.log(bar);  // [[ true,false],[true,false]]  (wtf?)
atkayla
  • 8,143
  • 17
  • 72
  • 132

1 Answers1

2

In the first case you have created two separate arrays with [] syntax, which are separate references to the separate objects. But the case is another with Array#fill.

Array#fill works with a single value. When you pass an array into the fill function to fill the outer array, only single array is created and its going to fill all items in the outer array. This means that two references of the single array are inserted in the outer array.

We can see it comparing the references of the first and second array.

var bar = Array(2).fill(Array(2).fill(false));

console.log(bar[0] === bar[1]);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112