JavaScript Массив sort()
// Создаем массив
const fruits = ["Банан", "Апельсин", "Яблоко", "Манго"];
// Сортируем массив
fruits.sort();
Try it Yourself »
More Examples Below !
Description
The sort()
method sorts the elements of an array.
The sort()
method sorts the elements as strings in alphabetical and ascending order.
The sort()
method overwrites the original array.
See Also:
Sort Compare Function
Sorting alphabetically works well for strings ("Яблоко" comes before "Банан").
But, sorting numbers can produce incorrect results.
"25" is bigger than "100", because "2" is bigger than "1".
You can fix this by providing a "compare function" (See examples below).
Syntax
array.sort(compareFunction)
Parameters
Parameter | Description |
compareFunction |
Optional. A function that defines a sort order. The function should return a negative, zero, or positive value, depending on the arguments:
When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. Example: The sort function will sort 40 as a value lower than 100. When comparing 40 and 100, sort() calls the function(40,100). The function calculates 40-100, and returns -60 (a negative value). |
Return Value
Type | Description |
Array | The array with the items sorted. |
More Examples
Sort Decending
Sort and then reverse the order:
// Создаем массив
const fruits = ["Банан", "Апельсин", "Яблоко", "Манго"];
// Сортируем массив
fruits.sort();
// Переворачиваем массив
fruits.reverse();
Try it Yourself »
Numeric Sorts
Using a Sort Function
Sort numbers in ascending order:
// Создаем массив
const points = [40, 100, 1, 5, 25, 10];
// Сортируем массив
points.sort(function(a, b){return a-b});
Try it Yourself »
Sort numbers in descending order:
// Создаем массив
const points = [40, 100, 1, 5, 25, 10];
// Сортируем массив
points.sort(function(a, b){return b-a});
Try it Yourself »
Find the lowest value:
// Создаем массив
const points = [40, 100, 1, 5, 25, 10];
// Сортируем числа в порядке возрастания
points.sort(function(a, b){return a-b});
let lowest = points[0];
Try it Yourself »
Find the highest value:
// Создаем массив
const points = [40, 100, 1, 5, 25, 10];
// Сортируем числа по убыванию:
points.sort(function(a, b){return b-a});
let highest = points[0];
Try it Yourself »
Find the highest value:
// Создаем массив
const points = [40, 100, 1, 5, 25, 10];
// Сортируем числа по возрастанию:
points.sort(function(a, b){return a-b});
let highest = points[points.length-1];
Try it Yourself »
Array Tutorials:
Browser Support
sort()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |