Created
May 22, 2012 08:51
-
-
Save yefim/2767685 to your computer and use it in GitHub Desktop.
Sorts a string by the frequency of characters.
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 sort_by_freq = function(str) { | |
var i, j; | |
var map = []; | |
var sorted = []; | |
for (i = 0; i < str.length; i++) { | |
if (map[str.charAt(i)] == null) { | |
map[str.charAt(i)] = 1; | |
} else { | |
map[str.charAt(i)] = map[str.charAt(i)] + 1; | |
} | |
} | |
for (j in map) { | |
sorted.push([j, map[j]]); | |
} | |
sorted.sort(function(a,b) { return b[1] - a[1] }); | |
return sorted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment