Reduce is certainly one the most powerfull method we have at our disposal.
Here is a way to count get letters frequencies: Demo
const message = "This is a very short message"
const letters = message.split('').filter(l => l != ' ' );
const frequency = letters.reduce((acc, current) => {
acc[current] = (acc[current] || 0) + 1
return acc;
}, {})
console.log(frequency)
Top comments (3)
Could be shorter without reduce
Hy Eckehard, indeed your code is shorter and it is astute.
Reduce in largely use in functional reactive programming, when you iterate on'dynamic' streams,
and in this world 'for' type loops are of last resort
Finally it depends much on your personal preference. Sometimes it is good to "hide" some implementation details, but in general I prefer a code that shows the intention.
With reduce, I would expect an expression to return a single value, not an array. It´s possible, but maybe misleading.
We could also rewrite the code like this:
If I revisit such a code, it is much easier to know what it is doing. And the funciton has no exterrnal dependencies, which is also an advantage.