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.

6
  • 4
    Please edit your question to add a example of transactions. Commented Jul 20, 2021 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 Commented Jul 20, 2021 at 13:53
  • let totalIn = transactions.reduce((acc, cur) => acc + cur.amount, 0); is probably what you want Commented Jul 20, 2021 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. Commented Jul 20, 2021 at 13:55
  • Thanks for all responses. It's fixed now :) Commented Jul 20, 2021 at 13:59

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

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.