Skip to content

Instantly share code, notes, and snippets.

@MichaelDimitras
Created May 14, 2018 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelDimitras/49ef1da90deeac0aad00a6f6f19394e3 to your computer and use it in GitHub Desktop.
Save MichaelDimitras/49ef1da90deeac0aad00a6f6f19394e3 to your computer and use it in GitHub Desktop.
Sort characters by frequency
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