0

let totalIn = transactions.reduce((a, b) => Number(a.amount) + Number(b.amount));

What could be reasons that this is yielding NaN? Each object in the transactions array has an amount property and each amount property is holding a string that is convertible to a float.

  • 4
    Please [edit] your question to add a example of `transactions`. – 0stone0 Jul 20 '21 at 13:52
  • the second argument of reduce is also missing, which is the initial value but in the case of an object You should do it externally – DecPK Jul 20 '21 at 13:53
  • `let totalIn = transactions.reduce((acc, cur) => acc + cur.amount, 0);` is probably what you want – Sleepwalker Jul 20 '21 at 13:55
  • The correct code would be `let totalIn = transactions.reduce((total, item) => total += Number(item.amount), 0)`. You are misinterpreting the arguments of the reduce callback function and you did not initialize the accumulator. – secan Jul 20 '21 at 13:55
  • Thanks for all responses. It's fixed now :) – Stijn Klijn Jul 20 '21 at 13:59
  • Duplicate of [Calling reduce to sum array of objects returns NaN](https://stackoverflow.com/questions/39698450/calling-reduce-to-sum-array-of-objects-returns-nan) – Ivar Jul 20 '21 at 14:01

1 Answers1

5

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).

Pointy
  • 405,095
  • 59
  • 585
  • 614