Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
Setting value in 2D Array results in strange behaviour

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!