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

7 comments:

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

    --K

    ReplyDelete
  2. 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 ));

    ReplyDelete
  3. it worked cool :)

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

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

    ReplyDelete