3

I'm creating an array and populating it using the fill method but changing array1[0].foo changes all objects in the array.

const array1 = Array(2).fill({ foo: null })
array1[0].foo = 'bar' // [ { foo: 'bar' }, { foo: 'bar' } ]

Is there a way to use fill with different copies of the same object for every index?

Ramon Balthazar
  • 3,907
  • 3
  • 25
  • 34

1 Answers1

1

It does not work with Array#fill, because it uses a constant value.

You could use Array.from and map the object.

const array = Array.from({ length: 2 }, _ => ({ foo: null }));

array[0].foo = 'bar';

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392