EN
JavaScript - count character occurrences
7
points
In this article, we would like to show you how to count the number of characters that were used in some text using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const countCharacters = (input) => {
const counts = {};
for (const entry of input) {
const count = counts[entry] ?? 0;
counts[entry] = count + 1;
}
return counts;
};
// Usage example:
const input = 'This is some text...';
const counts = countCharacters(input);
for (const key in counts) {
console.log(key + ' ' + counts[key]);
}
Output:
T 1
h 1
i 2
s 3
3
o 1
m 1
e 2
t 2
x 1
. 3