DEV Community

loading...
Cover image for Day 17 of JavaScriptmas - Different Symbol Naive

Day 17 of JavaScriptmas - Different Symbol Naive

Sekti
Keep moving forward. Learn well not learn fast.
・1 min read

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;
}
Enter fullscreen mode Exit fullscreen mode

2nd - Use spread operator with Set

function differentSymbolsNaive(str) {
    let uniqLetters = [...new Set(str)];

    return uniqLetters.length;
} 
Enter fullscreen mode Exit fullscreen mode

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;
} 
Enter fullscreen mode Exit fullscreen mode

Or

Single line of code with Arrow Function

const differentSymbolsNaive = str => [...new Set(str)].length;
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app