I've been trying to come up with an answer to this exercise where I have to count the frequency of characters in a string.
Suppose I have a string "haphqap" and I want the output as "h2a2p2q1".
I am able to achieve with two for loops. If anyone can provide me with some efficient answer.
var strin = "haphqap";
var count = {}
for (var pos = 0; pos < strin.length; pos++) {
if (!(strin[pos] in count)) {
count[strin[pos]] = 1;
} else {
count[strin[pos]]++;
}
}
console.log(count) //{ h: 2, a: 2, p: 2, q: 1 }
Using this object I can make a string.
I want to know if there is any another way of doing it?