1. 🧐 Expected Output
--- Examples
maxChar("abcccccccd") === "c"
maxChar("apple 1231111") === "1"
2. 🤔 My Solution
function maxChar(str) {
const updatedStr = str.split("").filter(element => element !== '')
const result = {}
for (let index = 0; index < updatedStr.length; index++) {
const element = updatedStr[index]
if (element in result) {
result[element] ++
} else {
result[element] = 1
}
}
const resultKeys = Object.keys(result)
const resultValues = Object.values(result)
const max = Math.max(...resultValues)
resultKeys.forEach((val) =>{
if (result[val] === max) {
return val
}
})
}
3. 🎊 Best Solution
function maxChar(str) {
const result = {}
let max = 0
let maxChar = ''
for (const char of str) {
if (char in result) {
result[char] ++
} else {
result[char] = 1
}
}
for (let char in result) {
if (result[char] > max) {
max = result[char]
maxChar = char
}
}
return maxChar
}