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

139
Vistas
Why does a single assignment to one 2d array cell fill two cells at once in Javascript?

I have this code from this leetcode question:


function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number {
    
    const land: boolean[][] = new Array(n).fill(new Array(n).fill(false))
    console.log(land)
    
    dig.forEach(spot => {
        console.log(spot, spot[0], spot[1])
        land[spot[0]][spot[1]] = true
        console.log(land)
    })
    
    console.log(land)
    return 0

};

With this input

n = 2
artifacts = [[0,0,0,0],[0,1,1,1]]
dig = [[0,0],[0,1]]

With this stdout:

[ [ false, false ], [ false, false ] ]

[ 0, 0 ] 0 0

[ [ true, false ], [ true, false ] ] **but expected => [ [ true, false ], [ false, false ] ]

[ 0, 1 ] 0 1

[ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ]
[ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ]

Why do land[1][0] === true and land[1][1] === true when they are never accessed?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This:

  new Array(n).fill(new Array(n).fill(false))

fills the new outer array with n copies of the same array. The argument to the outer .fill() is computed once, so there's only one array involved for the second dimension.

You can create multiple arrays, one for each row:

const land: boolean[][] = new Array(n);
land.fill("dummy value");
land.forEach((_, i, rows) =>
  rows[i] = new Array(n);
  rows[i].fill(false)
);

In the (edited) code, the outer array is first filled with a dummy value. That's necessary because .forEach() will skip uninitialized entries in an array. Alternatively, a simple for loop could be used, though unless n is enormous it probably doesn't matter.

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