Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of occurrences in an array using reduce in javascript

I was trying to find a solution to find out the number of occurrences of a number in an array and came across the below solution:

const occurrences = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
  return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc
}, {});

console.log(occurrences)

The code above works as expected. But I am not able to understand properly how it works. Can someone please simplify and explain the reduce method above? Thanks in advance.

like image 649
pranami Avatar asked Dec 10 '25 08:12

pranami


1 Answers

I assume the tricky part is just:

return acc[curr] ? ++acc[curr] : acc[curr] = 1, acc

Note that this is just:

return (some_expression_with_side_effects), acc

...which returns acc. Take a look at the comma operator in JavaScript for details. In short, the expression a, b equals b. Using this as a return value for reduce just ensures that the the accumulator is always the same object acc. But we add properties to that object as we reduce.

As we reduce items in the array, the side-effect expression does the following:

  • if there is a count for the current item, then increment it
  • if there is not a count yet, then add it and initialize it to 1.

Note that we don't actually use the return value of ++acc[curr], we just rely on the side-effect that it actually increments the values stored at acc[curr]. And similarly, we don't return the value of the expression acc[curr] = 1, but rather, we rely on the side-effect that it actually sets acc[curr] to an initial value of 1.

like image 136
Wyck Avatar answered Dec 11 '25 20:12

Wyck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!