Open In App

JavaScript Program to Count the Occurrences of Each Character

Last Updated : 23 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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));

Output
Map(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)]);

Output
1
  • 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?

ApproachWhen to Use
Using ObjectBest for small-to-medium strings; simple and efficient.
Using MapUse when dealing with large datasets or non-string keys.
Using forEachSuitable when readability is a priority.
Using reduceGreat for functional programming but slightly less beginner-friendly.
Using Array (ASCII)Efficient for ASCII-only strings; avoid for Unicode.
Using RegExpUse for specific pattern-based counting but avoid for performance-critical apps.


Next Article

Similar Reads