JavaScript Array sort()
Příklady
Seřadit pole:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Seřadit a pak obrátit pořadí:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Definice a použití
Seřadí sort()
prvky pole.
sort()
Přepíše původní pole .
Seřadí sort()
prvky jako řetězce v abecedním a vzestupném pořadí.
Viz také:
Funkce porovnání řazení
Řazení podle abecedy funguje dobře pro řetězce ("Apple" je před "Banana").
Třídění čísel však může vést k nesprávným výsledkům.
"25" je větší než "100", protože "2" je větší než "1".
Můžete to opravit poskytnutím "funkce porovnání" (viz příklady níže).
Syntax
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). |
Návratová hodnota
Pole se seřazenými položkami. |
Další příklady
Seřadit čísla vzestupně:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Seřadit čísla v sestupném pořadí:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
Najděte nejnižší hodnotu:
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];
Najděte nejvyšší hodnotu:
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];
Najděte nejvyšší hodnotu:
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];
Podpora prohlížeče
sort()
je funkce ECMAScript1 (ES1).
ES1 (JavaScript 1997) je plně podporován ve všech prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |