Created
May 14, 2018 16:22
-
-
Save MichaelDimitras/49ef1da90deeac0aad00a6f6f19394e3 to your computer and use it in GitHub Desktop.
Sort characters by frequency
This file contains 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
var frequencySort = function(s) { | |
let charCounts = {}; | |
for(let i = 0; i < s.length; i++) { | |
if(charCounts[s[i]]) { | |
charCounts[s[i]] += 1; | |
} else { | |
charCounts[s[i]] = 1; | |
} | |
} | |
let freqs = Object.keys(charCounts); | |
freqs.sort((a,b) => { | |
return charCounts[b] - charCounts[a]; | |
}) | |
freqs = freqs.map(item => { | |
let accumulator = ''; | |
for(i = 0; i < charCounts[item]; i++) { | |
accumulator += item; | |
} | |
return accumulator; | |
}); | |
return freqs.join('') | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment