Home >>JavaScript Array Reference >JavaScript Array sort() Method
JavaScript sort() method is used to sort the items of a given input array according to the compare() function. If the function is not given then it sorts the values as strings in alphabetical and ascending order. It changes the original given array.
Syntax:array.sort(compareFunction)
Parameter | Description |
---|---|
compareFunction | This is an optional parameter. It defines a function that defines an alternative sort order. |
Method | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
sort() | Yes | Yes | Yes | Yes | Yes |
<html> <body> <p>Click the button to see the Output.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> var x = ["Bunny", "Mike", "Jerry", "Joker", "Alpha", "Delta"]; document.getElementById("demo").innerHTML = x; function myFunction() { x.sort(); document.getElementById("demo").innerHTML = x; } </script> </body> </html>
Click the button to see the Output.
<html> <body> <p>Click the button to see the Output.</p> <button onclick="myFunction1()">Try it</button> <p id="demo1"></p> <script> var num = [34, 96, 3, 6, 63, 1, 14]; document.getElementById("demo1").innerHTML = num; function myFunction1() { num.sort(function(a, b){return a-b}); document.getElementById("demo1").innerHTML = num; } </script> </body> </html>
Click the button to see the Output.