sortowanie tablicy JavaScript
Przykłady
Sortuj tablicę:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Sortuj, a następnie odwróć kolejność:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Definicja i użycie
Sortuje sort()
elementy tablicy.
Nadpisuje sort()
oryginalną tablicę.
Sortuje sort()
elementy jako ciągi w porządku alfabetycznym i rosnącym.
Zobacz też:
Sortuj Porównaj Funkcja
Sortowanie alfabetyczne działa dobrze w przypadku ciągów ("Apple" znajduje się przed "Bananem").
Jednak sortowanie liczb może dawać nieprawidłowe wyniki.
„25” jest większe niż „100”, ponieważ „2” jest większe niż „1”.
Możesz to naprawić, udostępniając „funkcję porównania” (patrz przykłady poniżej).
Składnia
array.sort(compareFunction)
Parametry
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). |
Wartość zwrotu
Tablica z posortowanymi elementami. |
Więcej przykładów
Sortuj liczby w kolejności rosnącej:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Sortuj numery w kolejności malejącej:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
Znajdź najniższą wartość:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order
points.sort(function(a, b){return a-b});
let lowest = points[0];
Znajdź najwyższą wartość:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in descending order:
points.sort(function(a, b){return b-a});
let lowest = points[0];
Znajdź najwyższą wartość:
const points = [40, 100, 1, 5, 25, 10];
// Sort the numbers in ascending order:
points.sort(function(a, b){return a-b});
let highest = points[points.length-1];
Obsługa przeglądarki
sort()
to funkcja ECMAScript1 (ES1).
ES1 (JavaScript 1997) jest w pełni obsługiwany we wszystkich przeglądarkach:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |