Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!