Below is the steps and function to print character and its occurences.
Steps to get the solution:
1. Create an
object named 'exists', which can be used as a hashMap in JavaScript
2. Loop over the items of string, add characters as key exists object with value as 1 which are not already present.
3. If character key is already present in exists object, increment the value for that key by 1.
4.Loop over the exists object and print the occurences using 'exists[item]' syntax, where 'item' is current item in exists object iteration.
Code:
const countOccurences=(str)=> {
let exists={}
for (let i= 0; i < str.length; i++) {
if(exists[str[i]]) {
exists[str[i]]+=1;
}
else {
exists[str[i]]=1;
}
}
for(let item in exists) {
console.log("occurences of "+item+" is :"+exists[item])
}
}
countOccurences('malayalam')
// output
occurences of m is :2
occurences of a is :4
occurences of l is :2
occurences of y is :1