Skip to content

Instantly share code, notes, and snippets.

@yefim
Created May 22, 2012 08:51
Show Gist options
  • Save yefim/2767685 to your computer and use it in GitHub Desktop.
Save yefim/2767685 to your computer and use it in GitHub Desktop.
Sorts a string by the frequency of 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