I have a simple piece of code below but it seems the same instance of the array is duplicated in each row, such that when I change the value in board[0][0] it somehow changes it in all rows.
How can I initialize the board correctly so that each row is unique?
Looking for a sleek solution or some tweak to mine as opposed to writing out all the numbers or having a for-loop or something. Or maybe the sleekest solution is to have a for-loop?
const n = 4;
let board = new Array(n).fill(new Array(n).fill(0));
board[0][0] = 1;
console.log(board)
Output:
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
>Solution :
The new Array(n).fill(0) is created once and then passed to .fill method, so indeed, you get n copies (references to be precise) of the same array in the result array. You could add map function to make n new arrays, like this:
new Array(n).fill(0).map(x => new Array(n).fill(0));
In this way, map creates new array every time, so you get n different arrays filled with 0.
Demonstration Snippet:
const n = 4;
let board = new Array(n).fill(0).map(x => new Array(n).fill(0));
board[0][0] = 1;
console.log(board)