over 9 years ago
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>
<!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:
Because sort() method sorts the values as strings in alphabetical.
Can you help out the community by solving one of the following Javascript problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
0 Comment(s)