0

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?

4
  • 1
    stackoverflow.com/questions/37949813/… Commented May 20, 2024 at 9:18
  • 1
    There's no such thing as a "primitive array" in JavaScript, arrays are objects. You get exactly the same array object whether you use the Array constructor or an array literal ([]). What's going on above is that fill puts the same array in every slot, whereas when you don't use fill, you're creating separate arrays for each slot. Commented May 20, 2024 at 9:19
  • 1
    If you want to create an array containing five different three-element arrays without writing array literals, you can use Array.from's mapping callback: const arr = Array.from({length: 5}, () => new Array(3).fill(0)); (or any of several variations). Commented May 20, 2024 at 9:21
  • Thanks for the tips makes complete sense after realizing arrays are references I also found this little code snippet that I thought was "clean" and made the 2d array's nicely 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)); Commented May 20, 2024 at 10:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.