Thursday 6 December 2012

sort json array

  • ascending descending order easy way to sort javascript array simple steps to sort json array in ascending descending order
Lets consider following example for sorting

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" }
];


code to sort json array


<script type="text/javascript">

    var arr = [
        { "ID": 135, "Name": "FGH", "Address": "34, Baker Street" },
        { "ID": 432, "Name": "ABC", "Address": "BLDG 1, J Street" },
        { "ID": 252, "Name": "DEF", "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

         Before Sorting
         135 FGH
         432 ABC
         252 DEF

         After Sorting
         432 ABC
         252 DEF
         153 FGH

No comments:

Post a Comment