JavaScript Program to Count the Occurrences of Each Character
Last Updated :
23 Nov, 2024
Here are the various methods to count the occurrences of each character
Using JavaScript Object
This is the most simple and widely used approach. A plain JavaScript object (obj) stores characters as keys and their occurrences as values.
JavaScript
const count = (s) => {
const obj = {};
for (const char of s) {
obj[char] = (obj[char] || 0) + 1;
}
return obj;
};
const s = "hello world";
console.log(count(s));
Output{ h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
- A loop iterates over each character in the string.
- For each character, check if it exists in the object. If yes, increment its count; otherwise, initialize it to 1.
Using Map
Using a Map provides better performance for large strings with many unique characters. It is also more structured and explicitly designed for key-value storage.
JavaScript
const count = (s) => {
const map = new Map();
for (const char of s) {
map.set(char, (map.get(char) || 0) + 1);
}
return map;
};
const s = "hello world";
console.log(count(s));
OutputMap(8) {
'h' => 1,
'e' => 1,
'l' => 3,
'o' => 2,
' ' => 1,
'w' => 1,
'r' => 1,
'd' => 1
}
- Similar to the object-based approach but uses Map’s set and get methods.
- Better suited where keys can have non-string data types.
Using forEach() with an Object
This approach uses forEach() to loop through characters and count their occurrences in an object. It’s a modern and slightly more readable version of the for...of loop.
JavaScript
const count = (s) => {
const obj = {};
[...s].forEach((char) => {
obj[char] = (obj[char] || 0) + 1;
});
return obj;
};
const s = "hello world";
console.log(count(s));
Output{ h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
- Spread the string into an array ([...s]) and iterate over it using forEach.
- Update character counts in the object.
Using reduce()
The reduce() method stores the result into an object. It’s a more functional programming-oriented approach.
JavaScript
const count = (s) => {
return [...s].reduce((obj, char) => {
obj[char] = (obj[char] || 0) + 1;
return obj;
}, {});
};
const s = "hello world";
console.log(count(s));
Output{ h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
- Use reduce() to build an object that keeps track of character counts.
- It’s clean and concise but can be harder to read for beginners.
Using Arrays and ASCII Mapping
This method is useful for counting ASCII characters by mapping their character codes to array indices.
JavaScript
const count = (s) => {
const a = Array(256).fill(0);
for (const char of s) {
a[char.charCodeAt(0)]++;
}
return a;
};
const s = "hello";
console.log(count(s)['h'.charCodeAt(0)]);
- Characters are mapped to array indices using their ASCII values (charCodeAt).
- Suitable only for ASCII strings and not recommended for Unicode.
Using Regular Expressions
Regular expressions can be used to count occurrences by matching a specific character repeatedly.
JavaScript
const count = (s) => {
const obj = {};
for (const char of new Set(s)) {
obj[char] = (s.match(new RegExp(char, "g")) || []).length;
}
return obj;
};
const s = "hello world";
console.log(count(s));
Output{ h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }
- Use RegExp to globally match each unique character in the string.
- Counts are stored in an object.
Which Approach Should You Use?
Approach | When to Use |
---|
Using Object | Best for small-to-medium strings; simple and efficient. |
Using Map | Use when dealing with large datasets or non-string keys. |
Using forEach | Suitable when readability is a priority. |
Using reduce | Great for functional programming but slightly less beginner-friendly. |
Using Array (ASCII) | Efficient for ASCII-only strings; avoid for Unicode. |
Using RegExp | Use for specific pattern-based counting but avoid for performance-critical apps. |
Similar Reads
JavaScript Program to Count the Occurrences of a Specific Character in a String In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript. Example: Input : S = âgeeksforgeeksâ and c = âeâOutput : 4Explanation: âeâ appears four times in str
3 min read
JavaScript Program to Count Number of Alphabets We are going to implement an algorithm by which we can count the number of alphabets present in a given string. A string can consist of numbers, special characters, or alphabets.Examples:Input: Str = "adjfjh23"Output: 6Explanation: Only the last 2 are not alphabets.Input: Str = "n0ji#k$"Output: 4Exp
3 min read
JavaScript Program to Print All Duplicate Characters in a String In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = âgeeksforgeeksâOutput:e, count = 4g, count = 2k, count = 2s, count = 2Ta
5 min read
JavaScript Program to Find Kâth Non-Repeating Character in String The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
6 min read
JavaScript Program Count number of Equal Pairs in a String In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
3 min read