EN
TypeScript - count character occurrences
3 points
In this article, we would like to show you how to count the number of characters that were used in some text using TypeScript.
Quick solution:
xxxxxxxxxx
1
const countCharacters = (text: string): Record<string, number> => {
2
const counts: Record<string, number> = {};
3
for (const entry of input) {
4
const count = counts[entry] ?? 0;
5
counts[entry] = count + 1;
6
}
7
return counts;
8
};
9
10
11
// Usage example:
12
13
const input = 'This is some text...';
14
const counts = countCharacters(input);
15
16
for (const key in counts) {
17
console.log(key + ' ' + counts[key]);
18
}
Output:
xxxxxxxxxx
1
T 1
2
h 1
3
i 2
4
s 3
5
3
6
o 1
7
m 1
8
e 2
9
t 2
10
x 1
11
. 3