Given a string, return the character that is most commonly used in the string.
maxChar("abcccccccd") === "c"
maxChar("apple 1231111") === "1"
Two ways to Convert string into a character map (an object)
forEach
helper to loop over all the charactersfor...of
loop to loop over all the characters
for...of
loop is used on array or string (iterable object)
for...in
loop is used on an actual objectobj[char]
: return a reference to that particular character or at least its value
function maxChar(str){
const obj = {};
for (let char of str){
if (!obj[char]){
obj[char] = 1;
} else {
obj[char]++;
}
}
}
function maxChar(str) {
const charMap = {};
let max = 0;
let maxChar = "";
// Build a character map
for (let char of str){
charMap[char] = charMap[char] + 1 || 1; // use boolean instead of if
}
// loop through an object
for (let key in charMap){
if (charMap[key] > max){
max = charMap[key];
maxChar = key;
}
}
return maxChar;
}
maxChar("abcccccccd")
maxChar("apple 1231111")