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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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?