Skip to content

Instantly share code, notes, and snippets.

@p-j-anderson
Last active Oct 15, 2020
Embed
What would you like to do?
javascript.reduce() - reduce group
const reduceOccurrences = manyNumbers.reduce((acc, cur) => {
acc[cur] ? acc[cur]++ : acc[cur] = 1
return acc
}, {})
@TylerRick

This comment has been minimized.

Copy link

@TylerRick TylerRick commented Oct 15, 2020

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

This comment has been minimized.

Copy link
Owner Author

@p-j-anderson p-j-anderson commented Oct 15, 2020

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