Last active
March 6, 2017 15:38
-
-
Save interdigitize/05d9cba174b597ea7f8a90ad7c782600 to your computer and use it in GitHub Desktop.
Sort Characters By Frequency— refactored
This file contains hidden or 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
//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