JavaScript sort()Method
Example
Array sorting:
fruits.sort();
fruitsOutput result:
Try it Yourself »
Definition and Usage
The sort() method is used to sort the elements of an array.
The sort order can be alphabetical or numeric, and in ascending or descending order.
The default sort order is alphabetical ascending.
Note:When numbers are sorted alphabetically, "40" will come before "5".
For numeric sorting, you must call it by passing a function as an argument.
The function specifies whether the numbers are sorted in ascending or descending order.
This may be hard to understand when put into words; you can learn more about it through the examples at the bottom of this page.
Note:This method changes the original array!
Browser Support
![]()
![]()
![]()
![]()
![]()
All major browsers support sort().
Syntax
Parameter Values
| Parameter | Description |
|---|---|
| sortfunction | Optional. Specifies the sort order. Must be a function. |
Return Value
| Type | Description |
|---|---|
| Array | A reference to the array. Note that the array is sorted in place and no copy is made. |
Technical Details
| JavaScript Version: | 1.1 |
|---|
More Examples
Example
Numeric sorting (numbers and ascending):
points.sort(function(a,b){return a-b});
points output result:
Try it Yourself »
Example
Numeric sorting (numbers and descending):
points.sort(function(a,b){return b-a});
points output result:
Try it Yourself »
Example
Numeric sorting (alphabetical and descending):
fruits.sort();
fruits.reverse();
fruits output result:
Try it Yourself »
Other Extensions
JavaScript Array Object