Created
March 6, 2015 03:37
-
-
Save boy3vil/e2fe336b21e6542496a1 to your computer and use it in GitHub Desktop.
jQuery sort JSON by value
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
<script type="text/javascript"> | |
var arr = [ | |
{ "ID": 135, "Name": "Fargo Chan", "Address": "34, Baker Street" }, | |
{ "ID": 432, "Name": "Aaron Luke", "Address": "BLDG 1, J Street" }, | |
{ "ID": 252, "Name": "Dilip Singh", "Address": "Hotel J, SE" } | |
]; | |
// Before Sorting | |
document.write("<b>Before Sorting </b><br/>"); | |
for (var n = 0; n < arr.length; n++) { | |
document.write(arr[n].ID + ' ' + arr[n].Name + '<br>'); | |
} | |
// ascending order | |
function SortByID(x,y) { | |
return x.ID - y.ID; | |
} | |
function SortByName(x,y) { | |
return ((x.Name == y.Name) ? 0 : ((x.Name > y.Name) ? 1 : -1 )); | |
} | |
// Call Sort By Name | |
arr.sort(SortByName); | |
document.write("<br/><b>After Sorting </b> <br/>"); | |
for(var n=0;n<arr.length;n++){ | |
document.write(arr[n].ID + ' ' + arr[n].Name + '<br>'); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment