Skip to content

Instantly share code, notes, and snippets.

@mjstromberg
Created October 23, 2021 04:26
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 mjstromberg/8f4edd906abfb737b30d62cebceaba63 to your computer and use it in GitHub Desktop.
Save mjstromberg/8f4edd906abfb737b30d62cebceaba63 to your computer and use it in GitHub Desktop.
function frequencySort(string = '') {
const charFreqMap = {};
for (let i = 0; i < string.length; i++) {
const char = string[i];
const isCharInCharMap = Boolean(charFreqMap[char]);
charFreqMap[char] = isCharInCharMap ? charFreqMap[char] + 1 : 1;
}
const charArray = [];
for (let char in charFreqMap) {
const frequency = charFreqMap[char];
const extrapolatedString = char.repeat(frequency);
charArray.push(extrapolatedString);
}
charArray.sort((a, b) => b.length - a.length);
return charArray.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment