Sorting a JSON Array

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

Sort JSON






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

7 comments:

cris said...

could you plz explain why we return 0,1,-1

--K

PAPs said...

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 ));

Anonymous said...

it worked cool :)

Anonymous said...

How can i do the same thing in java (not in jquery or java script).

Alice said...

Thanks!!!! :)

Abhijit Kalmegh said...

Thank you
this sorting code very useful for me
thanks again...

Keerthi Jeevanandam said...

How to pass the arr to the function?