Array.fill(Array) creates copies by references not by value [duplicate]

You could use Array.from() instead:

Thanks to Pranav C Balan in the comments for the suggestion on further improving this.

let m = Array.from({length: 6}, e => Array(12).fill(0));

m[0][0] = 1;
console.log(m[0][0]); // Expecting 1
console.log(m[0][1]); // Expecting 0
console.log(m[1][0]); // Expecting 0

Original Statement (Better optimized above):

let m = Array.from({length: 6}, e => Array.from({length: 12}, e => 0));

Leave a Comment