DEV Community

artydev
artydev

Posted on

The power of reduce : Counting letters frequencies.

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)
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
efpage profile image
Eckehard • Edited

Could be shorter without reduce

const message = "This is a very short message"

let freq = {}

message.split('').forEach(letter => freq[letter] = freq[letter] + 1 || 1)
delete(freq[' '])

console.log(freq)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
artydev profile image
artydev • Edited

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

Collapse
 
efpage profile image
Eckehard

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:

const message = "This is a very short message"

function letterFrequency(message){
    let freq = {}
    message.split('').forEach(letter => freq[letter] = freq[letter] + 1 || 1)
    delete(freq[' '])
    return freq
}

console.log(letterFrequency(message))
Enter fullscreen mode Exit fullscreen mode

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.