How to Count Unique Characters in a String in JavaScript?

Estimated read time 1 min read

In JavaScript, you can count the number of unique characters in a string using various methods. One way to do this is to use an object to keep track of the frequency of each character in the string, and then count the number of properties in the object.

Here’s an example of how you can count the number of unique characters in a string:

function countUniqueCharacters(str) {
  var charCount = {};
  for (var i = 0; i < str.length; i++) {
    var char = str.charAt(i);
    if (charCount[char]) {
      charCount[char]++;
    } else {
      charCount[char] = 1;
    }
  }
  return Object.keys(charCount).length;
}

var str = "Hello, World!";
console.log(countUniqueCharacters(str)); // 9

In the example above, we use a for loop to iterate through each character in the string, and then use an object charCount to keep track of the frequency of each character. If a character already exists in charCount, we increment its count by 1. If the character does not exist, we add it to charCount with a count of 1. Finally, we return the number of properties in charCount using the Object.keys method, which returns an array of the object’s own enumerable properties.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply