Sort an array:
The result of fruits will be:
More "Try it Yourself" examples below.
The sort() method sorts the items of an array.
The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a "compare function" (See "Parameter Values" below).
Note: This method changes the original array.
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
sort() | 1.0 | 5.5 | 1.0 | Yes | Yes |
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:
When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. Example: When comparing 40 and 100, the sort() method calls the compare function(40,100). The function calculates 40-100, and returns -60 (a negative value). The sort function will sort 40 as a value lower than 100. |
Return Value: | The Array object, with the items sorted |
---|---|
JavaScript Version: | 1.1 |
Sort numbers in an array in ascending order:
The result of points will be:
Sort numbers in an array in descending order:
The result of points will be:
Get the highest value in an array:
The result of points[0] will be:
Get the lowest value in an array:
The result of points[0] will be:
Sort an array alphabetically, and then reverse the order of the sorted items (descending):
The result of fruits will be: