Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • sort() method in JavaScript

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 210
    Comment on it

    sort()

    sort() method is used to sort the elements of an array in ascending or descending order. The elements of array sort as strings (in alphabetic and ascending order), by default.

    Example:

    var names=[garry, john, anny, harry];
    names.sort();
    

    This does not work for the numeric values as the method treats the numeric values as strings. To overcome this, there is a compareFunction.

    Syntax for compareFunction

    array.sort(function(a, b){return a-b});
    

    This function returns a value (negative , positive or zero depending on arguments). Then, sort() method sorts the elements of the array using returned value.

    Example:

    var num = [50, 10, 16, 75, 21, 1];
    num.sort(function(a, b){return b-a});
    

 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: