Last active
February 12, 2018 17:32
-
-
Save dragonza/e15f3db07ebcbbe3a2cd974f23be4d71 to your computer and use it in GitHub Desktop.
Find the most commonly used character in string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function maxChar(str) { | |
const charMap = {}; | |
let max = 0; | |
let maxChar = ''; | |
// create character map | |
for (let char of str) { | |
if (charMap[char]) { | |
// increment the character's value if the character existed in the map | |
charMap[char]++; | |
} else { | |
// Otherwise, the value of the character will be increamented by 1 | |
charMap[char] = 1; | |
} | |
} | |
// find the most commonly used character | |
for (let char in charMap) { | |
if (charMap[char] > max) { | |
max = charMap[char]; | |
maxChar = char; | |
} | |
} | |
return maxChar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment