Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda