Skip to content

Instantly share code, notes, and snippets.

@interdigitize
Last active March 6, 2017 15:38
Show Gist options
  • Save interdigitize/05d9cba174b597ea7f8a90ad7c782600 to your computer and use it in GitHub Desktop.
Save interdigitize/05d9cba174b597ea7f8a90ad7c782600 to your computer and use it in GitHub Desktop.
Sort Characters By Frequency— refactored
//Given a string, sort it in decreasing order based on the frequency of characters.
var test = "Aabb";
var frequencySort = function(s) {
var counter = {};
var sortedArr = [];
var theStr = "";
for(var i = 0; i < s.length; i++){
if(!counter.hasOwnProperty(s.charAt(i))){
counter[s.charAt(i)] = 1;
}
else{
counter[s.charAt(i)] += 1;
}
}
for(var char in counter){
sortedArr.push([char, counter[char]]);
}
sortedArr.sort(function(a, b){
return b[1] - a[1];
});
sortedArr.forEach(function(el){
while(el[1] > 0){
theStr += el[0];
el[1]--;
}
});
return theStr;
};
console.log(frequencySort(test));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment