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?)