Sometimes, we want to count the frequency of characters in a string using JavaScript.
In this article, we’ll look at how to count the frequency of characters in a string using JavaScript.
How to count the frequency of characters in a string using JavaScript?
To count the frequency of characters in a string using JavaScript, we can use the spread operator and the array reduce
method.
For instance, we write:
const counter = str => {
return [...str].reduce((total, letter) => {
if (!total[letter]) {
return {
...total,
[letter]: 1
}
} else {
return {
...total,
[letter]: total[letter] + 1
}
}
}, {});
};
console.log(counter("aabsssd"));
to define the counter
function that spreads the string to a character array.
Then we call reduce
on the array with a callback that checks whether total[letter]
already exists.
If it doesn’t exist, we add the [letter]
property and set it to 1.
Otherwise, we increment total[letter]
by 1 and return that object.
We set total
to an empty object as its initial value by setting that as the 2nd argument of reduce
.
Therefore, the console log logs
{
a: 2,
b: 1,
d: 1,
s: 3
}
Conclusion
To count the frequency of characters in a string using JavaScript, we can use the spread operator and the array reduce
method.