Javascript String get common letter

Description

Javascript String get common letter

function mostCommonLetter(str){

 var max = 0;/*from   w w  w.j  a  va 2 s. c  o  m*/
 var letterPlaceHolder;
 var obj = {};

 for(var i = 0; i < str.length; i++){
   obj[str[i]] = obj[str[i]] ? obj[str[i]] + 1 : 1;

   if(obj[str[i]] > max){
      max = obj[str[i]];
      letterPlaceHolder = str[i];
   }
 }
   return [letterPlaceHolder, max];
}
console.log(mostCommonLetter('abca'));
console.log(mostCommonLetter("abbab"));
console.log(mostCommonLetter("abcde"));



PreviousNext

Related