-2

I have an array of objects that I initialize like so:

const balances = Array(5).fill({})

Later, I modify the balance for the first object using:

balances[0]['USD'] = 1000

I expect this to change only the balance for the first index. Instead, the 'USD' key is set for all of the elements:

balances // [{USD: 1000}, {USD: 1000}, {USD: 1000}, {USD: 1000}, {USD: 1000}]

// when I expected this:
balances // [{USD: 1000}, {}, {}, {}, {}]
FloatingRock
  • 6,741
  • 6
  • 42
  • 75

2 Answers2

1

You're filling the array with the same object. (We can see this by using the === strict equality operator.)

> balances = Array(5).fill({})
(5) [{…}, {…}, {…}, {…}, {…}]
> balances[0] === balances[1]
true

You'll need to construct an object for each slot - an FP (if not necessarily pretty or efficient) way to do this would be

> balances = Array(5).fill(null).map(() => ({}))
(5) [{…}, {…}, {…}, {…}, {…}]
> balances[0] === balances[1]
false

A non-FP, old-school, imperative but plenty fast (79% faster than the one above, by one quick benchmark) way is simply

var balances = [];
for(let i = 0; i < 5; i++) balances.push({});
AKX
  • 152,115
  • 15
  • 115
  • 172
1

You can use Array.from with a mapping function to fill the array with different objects.

const balances = Array.from({length: 5}, _=>({}));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80