count unique characters in string in typescript

index.ts
const str = "hello world";
const uniqueChars = new Set(str);
console.log(uniqueChars.size); // output: 9
105 chars
4 lines

In the above code block, we first define a string str with value "hello world". We then create a Set object called uniqueChars and pass in str as an argument. A Set object will only store unique values, so uniqueChars will contain all the unique characters in str. Finally, we log the size of uniqueChars, which will give us the count of unique characters in str.

We can also do this using a loop:

index.ts
const str = "hello world";
const uniqueChars = [];
for(let char of str) {
  if(!uniqueChars.includes(char)) {
    uniqueChars.push(char);
  }
}
console.log(uniqueChars.length); // output: 9
190 chars
9 lines

In this code block, we first define a string str with value "hello world". We then create an empty array called uniqueChars. We loop through each character in str using a for...of loop, and check if the character is already in the uniqueChars array using the includes() method. If not, we push the character into uniqueChars. Finally, we log the length of uniqueChars, which will give us the count of unique characters in str.

gistlibby LogSnag