The .reduce()
method passes the accumulator value as the first parameter. After the first iteration, therefore, a
will not be one of the values in your array: it will be the numeric sum of two numbers. Therefore it won't have an "amount" property, so Number(a.amount)
will be NaN
.
The way I personally would deal with that would be to ensure that every iteration is the same:
let totalIn = transactions.reduce((a, b) => a + Number(b.amount), 0);
By passing in a second parameter to .reduce()
to be used as the initial value of the accumulator, every call to the reduce callback will be similar (a number as a
and one of your array element objects as b
).