Max Char
Given a string, return the character that is most commonly used in a string
Example:
maxChar(‘appcccccccle’) = “c”
maxChar(‘hello 11111111’) = “1”
function maxChar(str){
const charMap = {};
let max = 0;
let maxChar = '';
for(let char of str){
if(charMap[char]){
charMap[char] ++;
}
else {
charMap[char] = 1;
}
}
for (let char in charMap) {
if(charMap[char] > max) {
max = charMap[char]
maxChar = char;
}
}
return maxChar;
}
We create a function maxChar with a parameter str
First we will use str param to fill the charMap object via looping
for (let char of str)
if the letter is found we increment charMap[char]++ will populate the charMap
else it will return 1;
Here is an example how it will look like:
Example “Hello World!”
{
H:1,
e:3,
l:2,
o:1,
““:1,
t:1,
h:1,
r:1,
!:1
}
Hint: for of we use it for arrays and for in we use it for objects.
Then we use another loop to loop through charMap(object).
We create 2 temporary variables max = 0 and maxChar = ‘’;
We loop through charMap and if values of charMap shown above in the example are greater than max
( which is 0)
So max takes the value of the string with max value. Like in the example above first charMap[0] > max
which it is it. H:1 1 > 0 so max will be reassign to 1. then goes to e > 1 yes max = 3 ….
At the end maxChar = char;
And we return maxChar;