Javascript examples for Array:sort
The sort() method sorts the items of an array.
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This method changes the original array.
array.sort(compareFunction)
Parameter | Description |
---|---|
compareFunction | Optional. A function that defines an alternative sort order. |
The function should return a negative, zero, or positive value, depending on the arguments, like:
function(a, b){return a-b}
The Array object, with the items sorted
The following code shows how to Sort an array in descending order
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> var fruits = ["a","b","c","d","e"]; document.getElementById("demo").innerHTML = fruits; function myFunction() {//from ww w . j a v a 2s.c o m fruits.sort(); fruits.reverse(); document.getElementById("demo").innerHTML = fruits; } </script> </body> </html>