Running the below code leads to an unexpected result where all 0th indexes are set to 6
let arr = new Array(5);
arr.fill(new Array(3).fill(0)); // 5x3 array of all 0's
arr[0][0] = 6;
console.log(arr);
// Somehow it edits every 0ith position [ [ 6, 0, 0 ], [ 6, 0, 0 ], [ 6, 0, 0 ], [ 6, 0, 0 ], [ 6, 0, 0 ] ]
If I use a primitive array, only index 0,0 is set to 6 (which is expected):
let arr = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
];
arr[0][0] = 6;
console.log(arr);
// Works as expected: [ [ 6, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ]
Any idea what I might be doing wrong? Or I am just missing something obvious?
Arrayconstructor or an array literal ([]). What's going on above is thatfillputs the same array in every slot, whereas when you don't usefill, you're creating separate arrays for each slot.Array.from's mapping callback:const arr = Array.from({length: 5}, () => new Array(3).fill(0));(or any of several variations).let len1 = 5;let len2 = 3;// The fill() is VERY IMPORTANT as map will not work an empty array. Fill sets it to undefined.let arr2d = new Array(len1).fill().map(() => new Array(len2).fill(0));