Search This Blog

2026/08/09

Javascript count occurance of characters in sentence



var naam = "hare krishna hare krishna krishna krishna hare hare hare rama hare rama rama rama hare hare";

function countCharacters(namm) {
    var charCount = {};
    for (var i = 0; i < naam.length; i++) {
        var char = naam[i];
        if (charCount[char]) {
            charCount[char]++;
        } else {
            charCount[char] = 1;
        }
    }
    return charCount;
}
console.log(countCharacters(naam));

Output:
{
  h: 8,
  a: 16,
  r: 12,
  e: 8,
  ' ': 15,
  k: 4,
  i: 4,
  s: 4,
  n: 4,
  m: 4
}
Explanation:
The code defines a string `naam` containing the phrase "hare krishna hare krishna
krishna krishna hare hare hare rama hare rama rama rama hare hare".
The function `countCharacters` takes this string as input and counts the occurrences
of each character in the string.

It initializes an empty object `charCount` to store the character counts.
It then iterates through each character in the string, checking if the character
already exists in the `charCount` object. If it does, it increments the count;
if not, it initializes the count to 1. Finally, it returns the `charCount` object,
which contains the frequency of each character in the string. The output shows the
counts of each character, including letters and spaces.

No comments:

Post a Comment