How to get the number of occurrences of each letter in specified string in JavaScript ?

In this article, we are given a string, our task is to find the occurrence of a character in the string with the help of a user-defined function. 

Example:
Input : "hello"
Output : h occur 1 times
e occur 1 times
l occur 2 times
o occur 1 times
Explanation : here "hello" have 1 h, so it have 1 value.
as same e have 1, l have 2 , o have 1.
Example 2:
Input : "did"
Output: d occur 2 times
i occur 1 times

Approach 1: In this approach, we use a map data structure to store the number of times characters occur.

  • First, we initialize the map with a key for each character of the string, and the value for each is 0.
  • We iterate over the string and increment the value of the character.
  • Finally, print key-values of the map.

Example: This example shows the use of the above-explained approach.

Javascript
<script>
    //function to print occurrence of character
    function printans( ans )
    {
      for( let [ key ,value] of ans)
      {
        // if()
        console.log(`${key}  occurs  ${value} times` );
          
      }
    
    }
    
    // function count occurrence of character
    function count( str , outp_map )
    {
      for( let i = 0 ;i < str.length ;i++)
      { 
    
        let k = outp_map.get(str[i]);
        outp_map.set(str[i], k+1) ;
            
        
      }
      //calling  print function
      printans(outp_map);
    }
    
    //function create map to count character
    function count_occurs( test , callback )
    {
      //checking string is valid or not 
      if( test.length === 0 )
      {
        console.log(" empty string ");
        return ;
      }
      else
      { 
        // map for storing count values
        let ans = new Map();
        for( let i = 0 ;i < test.length;i++)
        {
          ans.set(test[i], 0);
        }
        
        callback( test ,ans);
        
      }
    
    }
    
    // test string 
    let test =  "helloworld";
    count_occurs( test ,count);
</script>

 Output:

h  occurs  1 times
e occurs 1 times
l occurs 3 times
o occurs 2 times
w occurs 1 times
r occurs 1 times
d occurs 1 times

Approach 2: In this approach, we use nested for loop to iterate over the string and count for each character in the string. 

  • First, initialize count with value 0 for the ith value of the string.
  • Now we iterate over the string if ith value matches with the character, increasing the count value by 1.
  • Finally, print the value of the count.

Example: This example shows the use of the above-explained approach.

Javascript
<script>
    // function that count character occurrences in string 
    function count_occur( str )
    {
      // checking string is valid or not 
      if( str.length == 0 )
      {
        console.log("Invalid string")
        return;
      }
      //cor loop to iterate over string
      for( let i = 0 ;i < str.length ;i++)
      { 
        //variable counting occurrence 
        let count = 0;
        for( let j = 0 ;j < str.length ;j++)
        {
          if( str[i] == str[j] && i > j  )
          {
           break;
          }
          if( str[i] == str[j]  )
          {
            count++;
          }
        }
        if( count > 0)
        console.log(`${str[i]} occurs ${count} times`);
        
      }
    
    }
    
    // test string
    let test_str = "gfghello";
    count_occur( test_str);
</script>

 Output:

g occurs 2 times
f occurs 1 times
h occurs 1 times
e occurs 1 times
l occurs 2 times
o occurs 1 times

Approach 3: Using Array.reduce() with Map:

Using Array.reduce() with Map, the approach iterates over each character of the string. It accumulates the count of each character in a Map object, using the character as the key and the count as the value, updating it as needed.

Example: In this example The function countLetters() splits the string into characters, then uses Array.reduce() with a `Map` to count occurrences. Output is a `Map` with letter counts.

JavaScript
function countLetters(str) {
    return str.split('').reduce((count, char) => {
        count.set(char, (count.get(char) || 0) + 1);
        return count;
    }, new Map());
}

const result = countLetters("w3wiki");
console.log(result);

Output
Map(7) {
  'G' => 2,
  'e' => 4,
  'k' => 2,
  's' => 2,
  'f' => 1,
  'o' => 1,
  'r' => 1
}

Approach 4: Using a Plain JavaScript Object

In this approach, we will use a plain JavaScript object to store the count of each character in the string. This method is similar to using a Map but utilizes a simpler data structure.

Steps:

  • Initialize an empty object.
  • Iterate over each character in the string.
  • If the character is already a key in the object, increment its value.
  • If the character is not a key in the object, add it with an initial value of 1.
  • Print the key-value pairs from the object.

Example Implementation:

JavaScript
// Function to count occurrences of characters using a plain object
function countOccurrencesWithObject(str) {
    // Initialize an empty object to store character counts
    let charCount = {};

    // Iterate over each character in the string
    for (let char of str) {
        // If the character already exists in the object, increment its count
        if (charCount[char]) {
            charCount[char]++;
        } else {
            // If the character doesn't exist in the object, add it with count 1
            charCount[char] = 1;
        }
    }

    // Print the character counts
    for (let char in charCount) {
        console.log(`${char} occurs ${charCount[char]} times`);
    }
}

// Test string
let testString = "hellojavascript";
countOccurrencesWithObject(testString);

Output
h occurs 1 times
e occurs 1 times
l occurs 2 times
o occurs 1 times
j occurs 1 times
a occurs 2 times
v occurs 1 times
s occurs 1 times
c occurs 1 times
r occurs 1 times
i occurs 1 times
p occurs 1 ti...