sort() method for Array in JavaScript is used to sort the elements in that array.
Syntax is as below:
1 | array.sort(compareFunction); |
compareFunction: Specifies a function that defines the sort order. The array is sorted lexicographically if this function is skipped
The lexicographic or lexicographical order is a generalization of alphabetical order of words based on the alphabetical order of their component letters.
Return Value:
Returns a sorted array.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 | <html> <head> <title>myArray in JavaScript - sort() Method</title> </head> <body> <script type="text/javascript"> var myArr = new Array ("JavaScript", "PHP", "WordPress", "HTML", "CSS"); var sortArray = myArr.sort(); document.write("<br />Sorted Array: " + sortArray); </script> </body> </html> |
Output: This will give the following output:
1 | Sorted Array: CSS,HTML,JavaScript,PHP,WordPress |
You can Try sort() method yourself here.