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

243
Vistas
Javascript 2D array - best way to initialize with values

I'm trying to create a 2D array visited to show where the code has already visited in the grid. The way I have it now is that each row in visited is a shallow copy. Changing the value in one row, changes in all of the rows. What's the best way to initialize the starting values in visited in this case?

let grid = 
  [
    ["0", "1", "0"],
    ["1", "0", "1"],
    ["0", "1", "0"],
  ]

let visited = new Array(grid.length).fill(new Array(grid[0].length).fill(false))

visited[0][1]= true

console.log(visited);

Output:

[
  [ false, true, false ],
  [ false, true, false ],
  [ false, true, false ]
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use map to create new array for each row

let grid = 
  [
    ["0", "1", "0"],
    ["1", "0", "1"],
    ["0", "1", "0"],
  ]

let visited = Array.from({length: grid.length}, () => Array(grid[0].length).fill(false))

visited[0][1]= true

console.log(visited);

Also you can replace new Array() with Array.from

i.e Array.from({length: grid.length}, () => Array(grid[0].length).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