Reputation: 1141
I have the following variable:
const currentMonthCreditArray = creditCards.flatMap(x => x.balance.filter(y => (new Date(y.balanceDate).getMonth() === new Date().getMonth())))
Which outputs the following when console logged:
{_id: "5fc4aa02959b1409f2edab69", newBalance: 300, balanceDate: "2020-11-30T08:14:58.035Z"}, {_id: "5fc51cb0bd4d9a0f6059bdbe", newBalance: 400, balanceDate: "2020-11-30T16:24:14.390Z"}]
What I want to do is take each of the 'newBalance' entries from the currentMonthCreditArray and reduce them down (i.e. add them together). However I can't figure out how to do it.
I have tried the following, which errors out:
const currentMonthFinal = currentMonthCreditArray.flatMap(x => x.balance.map(y => y.newBalance.reduce((a,b) => a + b, 0)))
Can anyone point out how to reduce my array into a variable - hopefully a simple one.. Thanks!
Upvotes: 0
Views: 41
Reputation: 79
Javascript reduce function only runs on Array.
const currentMonthFinal = credits.reduce((a,b) => a + b.newBalance, 0)
Upvotes: 0
Reputation: 4034
const currentMonthFinal = currentMonthCreditArray.reduce((acc, current) => acc += current.newBalance, 0)
Upvotes: 2