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

121
Vistas
JavaScript generate an empty dynamic sized 2D array

I am trying to create a dynamically sized, empty 2D grid using arrays that can have a percentage of one value at specific co-ordinates, and the remainder another value, all assigned post-generation. I have found a suitable solution, but wanted to gain some clarification on why the original implementation didn't work as intended.

The code that works:

const height = 5;
const width = 5;
const percentage = 0.2;    // control percentage of certain value

// grid construction
const grid = new Array(height).fill().map(element => new Array(width));

// grid population
for (let y = 0; y < height; y++) {
  for (let x = 0; x < width; x++) {
    const probability = Math.random();
    grid[y][x] = probability > percentage ? 'x' : 'o';
  }
}

console.log(grid);

/* Example Output:
[
  ['x', 'x', 'x', 'o', 'x'],
  ['o', 'o', 'x', 'x', 'x'],
  ['x', 'x', 'x', 'x', 'x'],
  ['x', 'x', 'x', 'x', 'x'],
  ['x', 'x', 'o', 'x', 'o']
]
*/

The issue arises when I change the 'grid construction' block:

const height = 5;
const width = 5;
const percentage = 0.2;    // control percentage of certain value

// grid construction (doesn't work as intended)
const row = new Array(width).fill();
const grid = new Array(height).fill(row);

// grid population
for (let y = 0; y < height; y++) {
  for (let x = 0; x < width; x++) {
    const probability = Math.random();
    grid[y][x] = probability > percentage ? 'x' : 'o';
  }
}

console.log(grid);

/* Example Output:
[
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x'],
  ['x', 'x', 'x', 'o', 'x']
]
*/

I think I understand why the first code block gives the desired result, but I can't for the life of me work out what is going wrong in the second example.

I would really appreciate some clarification on what is going on here.

Cheers :)

about 4 years ago · Santiago Gelvez
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