-
-
Save p-j-anderson/4a04d447bbad8b365f304e08caa1feec to your computer and use it in GitHub Desktop.
javascript.reduce() - reduce group
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const reduceOccurrences = manyNumbers.reduce((acc, cur) => { | |
acc[cur] ? acc[cur]++ : acc[cur] = 1 | |
return acc | |
}, {}) |
Good catch! You're probably correct on the hypothesis of how it got there. Fixed!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Noticed a typo:
What's the point of the
if
? It works fine without it:I think the
if
must have been left over by mistake when someone converted theif/else
from the beginner version in https://github.com/p-j-anderson/blog--javascript-reduce/blob/master/grouping.js into a ternary operator. The ternary operator is the replacement for theif/else
. So making that expression be the condition of anotherif
statement is a mistake.You should always return a sane accumulator value from each iteration of a
reduce
loop. Otherwise you can run into an error likeTypeError: Cannot read property '2' of undefined
in the next iteration.The code as-is is equivalent to:
It only gets away with it because the
if
condition is always a nonzero number and therefore always truthy... :)