Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the most frequent character in a string javascript

Assuming I have the following string "355385". I need a simple JavaScript that can tell me that the most mentioned character is 5. Thank you in advance.

I tried with this one but no results.

var exp = '355385' ;

var exps =exp.split("");

var expCounts = { };

for (var i=0;i<exp.length;i++)

{expCounts["_" + exps[i]] = (expCounts["_" + exps[i]] || 0) + 1 ;

if (expCounts==3) exps=exps[i]; }; exps;
like image 426
N4pster Avatar asked Mar 23 '14 11:03

N4pster


1 Answers

This will loop over every character in the string and keep track of each character's count and the character with the maximum count:

var exp = '3553853335' ;
var expCounts = {};
var maxKey = '';
for(var i = 0; i < exp.length; i++)
{
    var key = exp[i];
    if(!expCounts[key]){
     expCounts[key] = 0;
    }
    expCounts[key]++;
    if(maxKey == '' || expCounts[key] > expCounts[maxKey]){
        maxKey = key;
    }
}

console.debug(maxKey + ":" + expCounts[maxKey]);

Update: Here is an ES6 version that will handle strings where multiple character have the same max count

function maxCount(input) {
    const {max, ...counts} = (input || "").split("").reduce(
    (a, c) => {
        a[c] = a[c] ? a[c] + 1 : 1;
        a.max = a.max < a[c] ? a[c] : a.max;
        return a;
    },
    { max: 0 }
    );

    return Object.entries(counts).filter(([k, v]) => v === max);
}

Example (please excuse the crude output):

maxCount('--aaaa1111--').join(' | ').replace(/,/g, ':');

outputs 1:4 | -:4 | a:4

like image 155
row1 Avatar answered Sep 28 '22 09:09

row1