Skip to content

Instantly share code, notes, and snippets.

@p-j-anderson
Last active October 15, 2020 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p-j-anderson/4a04d447bbad8b365f304e08caa1feec to your computer and use it in GitHub Desktop.
Save p-j-anderson/4a04d447bbad8b365f304e08caa1feec to your computer and use it in GitHub Desktop.
javascript.reduce() - reduce group
const reduceOccurrences = manyNumbers.reduce((acc, cur) => {
acc[cur] ? acc[cur]++ : acc[cur] = 1
return acc
}, {})
@TylerRick
Copy link

Noticed a typo:

What's the point of the if? It works fine without it:

manyNumbers = [1, 1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7]
manyNumbers.reduce((acc, cur) => {
  acc[cur] ? acc[cur]++ : acc[cur] = 1
  return acc
}, {})
// => {1: 2, 2: 1, 3: 3, 4: 2, 5: 5, 6: 1, 7: 4}

I think the if must have been left over by mistake when someone converted the if/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 the if/else. So making that expression be the condition of another if 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 like TypeError: Cannot read property '2' of undefined in the next iteration.

The code as-is is equivalent to:

const reduceOccurrences = manyNumbers.reduce((acc, cur) => {
  if (acc[cur] ? acc[cur]++ : acc[cur] = 1) {
    return acc
  } else {
    // Don't return anything. The accumulator will be undefined in the next iteration.
  }
}, {})

It only gets away with it because the if condition is always a nonzero number and therefore always truthy... :)

@p-j-anderson
Copy link
Author

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