3

I created a 2D array (4x4) in Javascript like this:

let visited = new Array(4).fill(new Array(4).fill(false));
console.log(visited);

[
  [ false, false, false, false ],
  [ false, false, false, false ],
  [ false, false, false, false ],
  [ false, false, false, false ]
]

When I tried to update a single element, it ends up updating entire column. Why is this happening?

visited[0][0] = true;
console.log(visited);

You can see this repl

Expected:

[
  [ true, false, false, false ],
  [ false, false, false, false ],
  [ false, false, false, false ],
  [ false, false, false, false ]
]

Actual:

[
  [ true, false, false, false ],
  [ true, false, false, false ],
  [ true, false, false, false ],
  [ true, false, false, false ]
]
JAM
  • 740
  • 3
  • 15
  • 33

3 Answers3

2

The docs of Array.fill are your friend here:

Note all elements in the array will be this exact value.

This is telling you that each one of the sub-arrays are actually the SAME array. Thus, if you change one, you change them all.

Looking at the code below, you'll see that the first comparison is false, whereas the second comparison is true

console.log([false,false,false,false] ===[false,false,false,false])

const arr = new Array(4).fill([false,false,false,false]);

console.log(arr[0] === arr[1]);
Dancrumb
  • 26,597
  • 10
  • 74
  • 130
1

Construct your Matrix with loops, rather than new Array().fill()

  let visited = [];

  for (let i = 0; i < 4; i++) {
    visited.push([]);
    for (let j = 0; j < 4; j++) {
      visited[i].push(false);
    }
  }

  visited[0][0] = true;
  console.log(visited);
belferink1996
  • 53
  • 1
  • 9
1

my friend change the way you create the matrix, just checkout this variant with .map():

 let visited = 
    (new Array(4)).fill().map(function(){ return new Array(4).fill(false);});
    visited[0][0] = true;
    console.log(visited)
    
    0: (4) [true, false, false, false]
    1: (4) [false, false, false, false]
    2: (4) [false, false, false, false]
    3: (4) [false, false, false, false]

Peace :)

altoqueperro
  • 371
  • 2
  • 4