0

I instantiated a 2D array with the size 10x10, all values are set to false. I want some of the cells to carry the value true, best case would be a random assignation.

But if I set the value of a cell to true using array[x][y] = true;, all cells with the given y value are set to true.

Example:

Input:
x = 1
y = 2

Output:
[
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false],
    [false, false, true, false, false, false, false, false, false, false]
]

Any idea, why this is happening? I simply don't get it. Find my code below:

// define board size
let boardSize = [10, 10];

// create a 2D array with size 10x10 and all values false
let currentBoard = Array(boardSize[0]).fill(Array(boardSize[1]).fill(false));

// fill 3 random cells with value true
for(let i = 0; i < 3; i++){
    let x = Math.floor(Math.random() * boardSize[0]);
    let y = Math.floor(Math.random() * boardSize[1]);
    currentBoard[x][y] = true; // this line sets the value of every x at position y to true, not just x/y
    console.log(x + '/' + y); // x and y have distinct values
}
console.log(currentBoard);
stui
  • 353
  • 3
  • 15

1 Answers1

2

The problem is that the second Array.fill just refrences itself over and over again. You can fix that if you replace it with this:

let currentBoard = Array(boardSize[0]).fill([]).map(() => Array(boardSize[1]).fill(false));
YourBrainEatsYou
  • 979
  • 6
  • 16