Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Count occurrences of each character in a string using Javascript

Javascript count occurrences of each character in string

It’s common in programming that every developer needs to count each occurrence of a character in a string or sentence in some situation. In this article, we will study all the possible best ways to understand how to count occurrences of each character in a string using Javascript. For counting the character in the sentence or string we can use the following methods which are very easy and good

  1. Reduce method: To count each repeated character in the string or sentence. Also,
  2. Replace method
  3. Combination of set and map methods

Now let’s understand how the same methods can be implemented with an example

Solution 1:
The simplest way is we can use the reduce method with a ternary condition. Every character or letter can be used as the property name to the result object.

const occurenceByReduce = (param) => {
    return [...param].reduce((result, nextChar) => { 
            result[nextChar] = result[nextChar] ? result[nextChar] + 1 : 1; 
            return result 
        }, {}); 
}
console.log(occurenceByReduce("How are you?"));
// output
// {H: 1, o: 2, w: 1, " ": 2, a: 1, …}

 

Solution 2:
We can also use the replace method with regular expression. Replace method will loop the entire string or sentence, and inside the loop, there is a condition to check like if the character is coming inside the loop for the first time then count will be added like 1. If a character is already present in the object then it will be incremented. The isNaN() function determines whether a value is NaN or not.

// sol 1 by replace
const occurenceByReplace = (param) => {
    var countChar = {};
    param.replace(/\S/g, function(item) {
        countChar[item] = (isNaN(countChar[item]) ? 1 : countChar[item] + 1);
    });
    return countChar;
}
console.log(occurenceByReplace("How are you?"));
// output
// {H: 1, o: 2, w: 1, a: 1, r: 1, …}

Solution 3:
In the second solution, we can use the combination of set and map methods as follows. Define a function called occurenceBySet that accepts a string as a parameter.

const occurenceBySet = (param) => {
    let listOfChar = new Set(param.split('')),
        result = new Map(),
        count = 0;
    for (item of listOfChar) {
        for (var i = 0; i < param.length; i++) {
            if (item === param[i]) {
                count++;
            }
        }
        result.set(item, count);
        count = 0;
    }
    return result;
}
console.log(occurenceBySet('How are you?'));
// output
// Map(10) {"H" => 1, "o" => 2, "w" => 1, " " => 2, "a" => 1, …}

 

2 thoughts on “Count occurrences of each character in a string using Javascript

Comments are closed.