Skip to content

Instantly share code, notes, and snippets.

@mbeaty
Created September 15, 2011 06:04
Show Gist options
  • Save mbeaty/1218651 to your computer and use it in GitHub Desktop.
Save mbeaty/1218651 to your computer and use it in GitHub Desktop.
JSON object sort by single field
var sort_by = function(field, reverse, primer){
reverse = (reverse) ? -1 : 1;
return function(a,b){
a = a[field];
b = b[field];
if (typeof(primer) != 'undefined'){
a = primer(a);
b = primer(b);
}
if (a<b) return reverse * -1;
if (a>b) return reverse * 1;
return 0;
}
}
// Example:
// var homes = [
// {"h_id":"3",
// "city":"Dallas",
// "state":"TX",
// "zip":"75201",
// "price":"162500"},
// {"h_id":"4",
// "city":"Bevery Hills",
// "state":"CA",
// "zip":"90210",
// "price":"319250"},
// {"h_id":"5",
// "city":"New York",
// "state":"NY",
// "zip":"00010",
// "price":"962500"}
// ];
//
// var sortedHomes=homes.sort(sort_by('state', true, function(a){return a.toUpperCase()}));
// console.log(sortedHomes);
// Attribution: http://stackoverflow.com/questions/979256/how-to-sort-a-json-array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment