4

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 ]
]
0

3 Answers 3

4

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]);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

2 Comments

Nice! It can be even cleaner like this: let visited = (new Array(4)).fill().map(x => new Array(4).fill(false));
@JAM, for sure that is a clean way and more simple

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.