JavaScript sort() Method
Example
Array sorting:
var
fruits
=
[
"Banana"
,
"Orange"
,
"Apple"
,
"Mango"
]
;
fruits.
sort
(
)
;
fruits Output result:
Apple,Banana,Mango,Orange
Try it »
Definition and Usage
The sort() method is used to sort the elements of an array.
The sort order can be alphabetical or numerical, in ascending or descending order.
The default sort order is alphabetical ascending.
**Note:** When numbers are sorted alphabetically, "40" will come before "5".
To sort numerically, you must call it with a function as a parameter.
The function specifies whether the numbers are sorted in ascending or descending order.
This may be difficult to understand; 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
array
.sort(
sortfunction
)
Parameter Values
| Parameters | 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):
var
points
=
[
40
,
100
,
1
,
5
,
25
,
10
]
;
points.
sort
(
function
(
a
,
b
)
{
return
a
b
}
)
;
points output result:
1,5,10,25,40,100
Try it »
Example
Numeric sorting (numbers and descending):
var
points
=
[
40
,
100
,
1
,
5
,
25
,
10
]
;
points.
sort
(
function
(
a
,
b
)
{
return
b
a
}
)
;
points output result:
100,40,25,10,5,1
Try it »
Example
Numeric sorting (letters and descending):
var
fruits
=
[
"Banana"
,
"Orange"
,
"Apple"
,
"Mango"
]
;
fruits.
sort
(
)
;
fruits.
reverse
(
)
;
fruits output result:
Orange,Mango,Banana,Apple
Try it »
JavaScript Array object