Here’s a simple JSON Array of objects
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" }
];
Here’s an example of how to sort this JSON Array.
<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>
OUTPUT
Tweet
7 comments:
could you plz explain why we return 0,1,-1
--K
Keep in mind "case" of string, 'a'!='A', 'a'>'B'
So my sollition would be:
return ((x.title== y.title) ? 0 : ((x.title.toLowerCase()> y.title.toLowerCase()) ? 1 : -1 ));
it worked cool :)
How can i do the same thing in java (not in jquery or java script).
Thanks!!!! :)
Thank you
this sorting code very useful for me
thanks again...
How to pass the arr to the function?
Post a Comment