I am trying to initialize a two-dimensional array with empty arrays so I can add elements to them in a larger composition using Array.push
. However, when I add to the inner arrays, they all get added to. Here is a simple example:
const arr = Array(3).fill([]);
arr[0].push(42);
Now arr
is [[42],[42],[42]]
but I was hoping for [[42],[],[]]
.
I think the problem is Array.fill
is putting the same referenced empty array into each slot. How do I get fill to make a distinct empty array at each slot?