Approaching a Frequency Counter Coding Challenge.

"aaabccd" returns: 'a':3"hello world" returns: 'l':3"111addrt1z" returns: '1':4
function maxChar(str) { //we will be using a string input
const charMap = {} //our empty object
for (let char of str) { //sets the loop to go over each character
if (charMap[char]) {//check to see if a character is in the obj
charMap[char]++ //increase the counter if true
} else {
charMap[char] = 1 //set the value to 1 if it's a new character
}
}
return charMap;
}
function maxChar(str) { //we will be using a string input
const charMap = {} //our empty object
let maxChar = '' //start the variable as nothing
let max = 0 //we need something to compare the characters to
for (let char of str) { //sets the loop to go over each character
if (charMap[char]) {//check to see if a character is in the obj
charMap[char]++ //increase the counter if true
} else {
charMap[char] = 1 //set the value to 1 if it's a new character
}
}

for (let char in charMap) { //loops over each key in the object
if (charMap[char] > max) { //if the character occurs more than 0
max = charMap[char]; // 'max' is assigned that character
maxChar = char; //our maxChar variable is assigned to max
}
}
return maxChar;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store