Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Array sort() Method in JavaScript ?

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 278
    Comment on it

    sort() method is used for sorting the items of an array.It sorts the values as strings in alphabetical and ascending order.

    And sort() method sort alphabetic or numeric.

    you can take reference of bellow example.

    <!DOCTYPE html>
    <html>
    <body>
    
    <!-- here write a button  to sort the array -->
    <button onclick="myFunction()">Click To sort</button>
    
    <!-- here define a id  -->
    <p id="sort"></p>
    
    <script>
    //here define a variable of empname
    var empname = ["Joe", "Roy", "Mac", "Carlo"];
    document.getElementById("sort").innerHTML = empname;
    //here write a function to call sort() method
    function myFunction() {
        empname.sort();
        document.getElementById("sort").innerHTML = empname;
    }
    </script>
    
    </body>
    </html>
    

    output will come following:

    Carlo,Joe,Mac,Roy

    Because sort() method sorts the values as strings in alphabetical.

 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: