So I am learning how to return the most common character in a string. I know how to do it if there is only one character that appears the most-e.i, the "a" in "javascript" which appears twice and the rest of the characters appear only once. But if the string is 'javascript prototype', there are two characters that appear the most which are "p" and "t". I am using the _.invert() to get the value of the number in which letters appear the most and I though since "p" and "t" both equal 3 then I could return them. I expected the output to be
"p t"
// Return the character that is most common in a string
// ex. maxCharacter('javascript') == 'a'
// Return multiple characters that are most common in a string
// ex. maxCharacter('javascript prototype') == 'p t'
function maxCharacter(str) {
const charMap = {};
let maxNum = 0;
let maxChar = '';
str.replace(/\s/gi, '').split('').forEach(function(char){
if(charMap[char]){
charMap[char]++;
} else {
charMap[char] = 1;
}
});
for(let char in charMap){
if(charMap[char] > maxNum) {
maxNum = charMap[char];
maxChar = (_.invert(charMap))[maxNum];
}
}
return maxChar;
}
// Call Function
const output = maxCharacter('javascript prototype');
console.log(output);