0

I can't seem to figure out why my code only works when there's just 2 arrays being computed. But when I'm adding another array, I get a result of "NaN".

Here's my code:

cycleComputation (trades) {
  if (! trades.length) {
    return 0;
  }
    const ups = trades;
    if (ups.length) {
      return ups.map(net => {
        return {
          realized: parseFloat(net.realizedPL),
          unrealized: net.unrealizedPL ? parseFloat(net.unrealizedPL) : 0
        }
      })
      .reduce((a,b) => (a.realized + a.unrealized) + (b.realized + b.unrealized));
    } else {
      return 0;
    }
}
Jun Kuan
  • 41
  • 9
  • 1
    `.reduce((a,b) => a + b.realized + b.unrealized, 0)` <-- You need to add an initial value `0` .And `a` is the sum and it is a number. – adiga Sep 24 '20 at 07:48
  • this actually worked! thank you so much! – Jun Kuan Sep 24 '20 at 08:15
  • This is a common mistake with `reduce`. You always need to provide the initialValue parameter. If it is not provided, the first object in the array is considered as accumulator. So, it works if there are only two items in the array. After the first loop, `a` is a number. So, `a.realized` will return undefined and the sum returns `NaN` – adiga Sep 24 '20 at 08:18

0 Answers0