Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of arrays insert in all rows

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading