Skip to content

Instantly share code, notes, and snippets.

@ishahid
Created February 26, 2014 03:26
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 ishahid/9223007 to your computer and use it in GitHub Desktop.
Save ishahid/9223007 to your computer and use it in GitHub Desktop.
Generic way of sorting JSON array by attribute
function sort_by(attr) {
return function(a, b) {
if( a[attr] > b[attr]) {
return 1;
} else if( a[attr] < b[attr] ) {
return -1;
}
return 0;
}
}
json_array = [
{"id": 1, "name": "Mike"},
{"id": 2, "name": "Bob"},
{"id": 3, "name": "Kate"},
];
json_array.sort(sort_by('id'));
json_array.sort(sort_by('name'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment