-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}, {}, {}, {}, {}]
2
  • Why the downvote? Commented Apr 14, 2021 at 19:08
  • 1
    fill uses the same exact value for every slot in the array. So a reference to the same object. Commented Apr 14, 2021 at 19:08

2 Answers 2

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({});
Sign up to request clarification or add additional context in comments.

Comments

1

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

const balances = Array.from({length: 5}, _=>({}));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.