Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda