Find the Number of Occurrence of Characters in a String in NodeJS

To get the number of unique characters in a string in NodeJS, loop through the string array, and in each iteration check if the character key is present in an object.

If the character key is not present in the object, set it to 1 (to indicate the first occurrence). If the character is present, increment its value.

function getUniqueCharDetails(str){
    var uniqueCharDetails = {};
    for (let i=0;i<str.length;i++){
        if(uniqueCharDetails[str[i]] == null){
            uniqueCharDetails[str[i]] = 1;
        }
        else {
            uniqueCharDetails[str[i]] = ++uniqueCharDetails[str[i]];
        }
    }
    return uniqueCharDetails;
}

console.log(getUniqueCharDetails('AABBCCFG'));
//Output: { A: 2, B: 2, C: 2, F: 1, G: 1 }

console.log(getUniqueCharDetails('RADAR'));
//Output: { R: 2, A: 2, D: 1 }

Note that this function is case sensitive:

console.log(getUniqueCharDetails('AaBBbCCFG'));
//Output: { A: 1, a: 1, B: 2, b: 1, C: 2, F: 1, G: 1 }
var uniqueCharDetails = {} declares an Object
var uniqueCharDetails = [] declares an Array.

An array in JavaScript can be considered as a subclass of Objects. In fact, if you check it will return an object.

console.log(typeof []);
//Output: object
Nithya Binoy

Nithya Binoy