sathish kumar sathish kumar - 7 months ago 7
Javascript Question

How to get the repeated letter in a string?



var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh";





Here I want to get the maximum and minimum entered values.For example, I have entered letter "a" as 10 times. That was the maximum. So I want to pint that value. How can I get the maximum entered values in a String using jquery or javascript.

Answer

A proposal with Array#forEach() and an object count:

var a = "aaaaaaaaaabbffddcccuuekkjjmlotcfshhh",
    count = {}, min, max;

a.split('').forEach(function (a) {
    count[a] = (count[a] || 0) + 1;
});
Object.keys(count).forEach(function (a, i) {
    if (!i) {
        min = [a];
        max = [a];
        return;
    }
    if (count[a] < count[min[0]]) {
        min = [a];
        return;
    }
    if (count[a] > count[max[0]]) {
        max = [a];
        return;
    }
    if (count[min[0]] === count[a]) {
        min.push(a);
    }
    if (count[max[0]] === count[a]) {
        max.push(a);
    }
});

document.write('min: ' + min.join(', ') + ' with occurrence of ' + count[min[0]] + '<br>');
document.write('max: ' + max.join(', ') + ' with occurrence of ' + count[max[0]] + '<br>');
document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');

Comments