Skip to content

Instantly share code, notes, and snippets.

@xjamundx
Created April 20, 2011 00:30
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 xjamundx/930065 to your computer and use it in GitHub Desktop.
Save xjamundx/930065 to your computer and use it in GitHub Desktop.
fancy object sort example
var locations = {
seattle: {reviews:[{title:"c"}]},
portland: {reviews:[{title:"v"}]},
provo: {reviews:[{title:"c"}]},
};
sort(locations).by("title").on("reviews");
function sort(obj) {
sort.obj = obj;
sort.by = function(field) {
sort.field = field;
return sort;
}
sort.on = function(arrayKey) {
for (var i in sort.obj) {
obj[i][arrayKey].sort(sortBy(sort.field));
};
return sort;
}
return sort;
}
function sortBy(field) {
if (!sortBy.fields) sortBy.fields = {};
if (sortBy.fields[field]) return sortBy.fields[field];
sortBy.fields[field] = function(a, b) {
a = a[field].toLowerCase()
b = b[field].toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
return sortBy.fields[field];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment