Skip to content

Instantly share code, notes, and snippets.

@dragonza
Last active February 12, 2018 17:32
Show Gist options
  • Save dragonza/e15f3db07ebcbbe3a2cd974f23be4d71 to your computer and use it in GitHub Desktop.
Save dragonza/e15f3db07ebcbbe3a2cd974f23be4d71 to your computer and use it in GitHub Desktop.
Find the most commonly used character in string
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