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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With