0

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?

Jeff E
  • 658
  • 1
  • 8
  • 19

1 Answers1

0

You can use Array#map.

const arr = [...Array(3)].map(_ => []);
arr[0].push(42);
console.log(arr);

Or Array.from.

const arr = Array.from({length: 3}, _ => []);
arr[0].push(42);
console.log(arr);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80