0

The code below is supposed to count the # of 4 in the numbers array. Why does the one with the acc++ not give the expected behavior?

>>>   numbers
(7) [1, 2, 3, 4, 5, 4, 4]
>>>   numbers.filter(n => n === 4).reduce( (acc, num) => acc = acc + 1, 0)
3
>>>   numbers.filter(n => n === 4).reduce( (acc, num) => acc++, 0)
0
Vlad
  • 1
  • 3
  • 2
    because of the order of `++` on the left side it adds in advance and retuns the new value. on the right side, it returns the value first and increment later. – Nina Scholz Nov 17 '20 at 22:30
  • 2
    You want `(acc) => acc + 1` as the callback. But really you should use just `.length` instead of that reduction, or even better `numbers.reduce((acc, num) => acc + (num == 4), 0)` – Bergi Nov 17 '20 at 22:31
  • @Bergi `(acc) => ++acc` works too, which solves the typo that the OP had – Samathingamajig Nov 17 '20 at 22:32
  • Thanks for the feedback! the side of the ++ mattered. Thought that it didn't count in this case for some reason. – Vlad Nov 17 '20 at 22:32
  • @Samathingamajig Yes, that would work as well, but one should not mutate the accumulator in a `reduce` call. `1+acc` or `acc+1` is the way to go. – Bergi Nov 17 '20 at 22:33
  • Thanks @Phil for finding the appropriate canonical faster than I could – Bergi Nov 17 '20 at 22:34
  • 1
    @Bergi why shouldn't you "mutate the accumulator in a `reduce` call"? The only time the value actually changes is the return of the callback each time, so it doesn't corrupt any data or anything. – Samathingamajig Nov 17 '20 at 22:37
  • 1
    @Samathingamajig a) as you say it's unnecessary, so you shouldn't do it b) when using `reduce` one wants to follow the functional programming paradigm, which favours immutability. – Bergi Nov 17 '20 at 22:46
  • @Bergi im just getting started with js, but respect for the neat code optimization. Thank you – Vlad Nov 17 '20 at 22:47

0 Answers0