0

When I create an array of empty arrays with the following code:

const arrayOfArrays = new Array(3).fill([])

As expected, I get [[],[],[]. However let's say I change the value with:

arrayOfArrays[0][0] = 'foo'

I expect to get [['foo'],[],[]] but I end up with [['foo'],['foo'],['foo']]. Why is this the case? How can I get it so that it works as expected?

avatarhzh
  • 2,175
  • 4
  • 21
  • 32
  • Use `Array.from` instead – CertainPerformance Aug 11 '19 at 09:08
  • @CertainPerformance this is no duplicate to the question you posted, this is actually the exact opposite question... – Gibor Aug 11 '19 at 09:15
  • 1
    @Gibor It's the same. OP is trying to create an array of arrays - to add the same element (an array) to another array 3 times. As described in the linked answer, `.fill` doesn't work well with non-primitives because then there are multiple copies of the *exact same object* in memory, so mutations to one object affects all objects in the array, as OP is experiencing here. The solution is to create a new object on each iteration, which can be done concisely with `Array.from` – CertainPerformance Aug 11 '19 at 09:20

0 Answers0