Created
February 26, 2014 03:26
-
-
Save ishahid/9223007 to your computer and use it in GitHub Desktop.
Generic way of sorting JSON array by attribute
This file contains hidden or 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
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