stumped
stumped

Reputation: 3293

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 ]
]

Upvotes: 0

Views: 406

Answers (1)

Code Maniac
Code Maniac

Reputation: 37755

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))

Upvotes: 2

Related Questions