Day 17 is to collect the number of unique characters in a word/sentence.
For instance, a word cabca
will have 3 different unique characters a
,b
, and c
which going to return 3
.
There are 2 methods to calculate unique characters using JavaScript
1st - Comparing Empty array with existing Array
function differentSymbolsNaive(str) {
let uniqLetters = [];
let strArr = str.split('');
strArr.map(letter => {
if (!uniqLetters.includes(letter)) {
uniqLetters.push(letter)
}
});
return uniqLetters.length;
}
2nd - Use spread operator with Set
function differentSymbolsNaive(str) {
let uniqLetters = [...new Set(str)];
return uniqLetters.length;
}
Personally, the 2nd approach is much easier and less code.
But the 1st one is more explicit and much easier to understand for beginner.
Even the 2nd approach can be shorten
2nd - Use spread operator with Set -- Shorten
function differentSymbolsNaive(str) {
return [...new Set(str)].length;
}
Or
Single line of code with Arrow Function
const differentSymbolsNaive = str => [...new Set(str)].length;
Top comments (0)