Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is difference between sorting string array and sorting numerical array in jQuery?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 133
    Comment on it

    Hello Readers,

    sorting string array :

    sort method in jquery is used to sort array elements in alphabetically order this type of sorting is called as sorting through string array.

    For Example :

    $(document).ready(function(){
    var list = [ Apple,Orange,Banana];
    
    $(#mydiv).html(list.join());
    list = list.sort();
    $(#sorted).html(list.join());
    });
    

    Output before sorting :

    Apple
    Orange
    Banana
    

    Output after sorting :

    Apple
    Banana
    Orange
    

    sorting numerical array :

    numerical array sorting in jquery is used to sort the numeric elements.

    For Example :

    $(document).ready(function(){
    var list = [ 20,3100,50];
    
    $(#mydiv).html(list.join());
    list = list.sort();
    $(#sorted).html(list.join());
    });
    

    Output before sorting :

    100
    20
    3
    50
    

    In the above code, sort method not sort the numerical array in proper order because sort method sorts on the basis of ASCII values.

    So, to sort the numerical value in proper order we use the comparison function with sort().

    For Example :

    Output after sorting in numerical array :

    $(document).ready(function(){
    var list = [ 20,3100,50];
    
    $(#mydiv).html(list.join());
    list = list.sort(function(a,b){
    return a-b;
    });
    
    $(#sorted).html(list.join());
    });
    

    Output before sorting :

    3
    20
    50
    100
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: