0

I currently have to functions which use the Array.reduce method but only the first function works.

let profit = incomes.reduce((a,b) => a.getAmount() + b.getAmount());

Where a = a custom BudgetItem class with the method getAmount. I am wondering if this is a common JS thing or if I am doing something wrong.

Please note I have checked with the debugger and entering this line I have the same data in both methods.

JoshR
  • 69
  • 1
  • 7
  • 4
    `a` becomes a Number after first iteration, which has no `getAmount` property - do `let profit = incomes.reduce((a,b) => a + b.getAmount(), 0);` instead – Bravo Dec 01 '20 at 23:39
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+reduce+sum+with+method+calls+not+working) of [Javascript reduce on array of objects](https://stackoverflow.com/q/5732043/4642212). – Sebastian Simon Dec 02 '20 at 00:10

1 Answers1

1

According to mozilla the first parameter in Array.reduce() is the accumulator (the current sum) and the second is the current value from the array

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce


So if you are trying to total the value from an array of BudgetItem you will want something like:

let profit = incomes.reduce((currentTotal, curremtIncome) => currentTotal + curremtIncome.getAmount());
BudBurriss
  • 136
  • 5