JavaScript Array sort()
Example
Sort an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The sort() method sorts the elements 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).
sort() overwrites the original array.
Browser Support
sort() is fully supported in all browsers:
| Chrome | IE | Edge | Firefox | Safari | Opera |
| Yes | Yes | Yes | Yes | Yes | Yes |
Syntax
array.sort(compareFunction)
Parameter Values
| 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. |
Technical Details
| Return Value: | The Array object, with the items sorted |
|---|---|
| JavaScript Version: | ECMAScript 1 |
More Examples
Example
Sort numbers in an array in ascending order:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Try it Yourself »
Example
Sort numbers in an array in descending order:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
Try it Yourself »
Example
Find the lowest value in an array:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order
points.sort(function(a, b){return a-b});
// points[0] = 1 (the lowest value)
Try it Yourself »
Example
Find the highest value in an array:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in descending order:
points.sort(function(a, b){return b-a});
// points[0] = 100 (the highest value)
Try it Yourself »
Example
Find the highest value in an array:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order:
points.sort(function(a, b){return a-b});
// points[points.length-1] = 100 (the highest value)
Try it Yourself »
Example
Sort an array alphabetically, and then reverse the order:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Try it Yourself »

