JavaScript array sort()
Esempi
Ordina matrice:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Ordinare e quindi invertire l'ordine:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Definizione e utilizzo
Ordina gli sort()
elementi di un array.
sort()
Sovrascrive l'array originale .
Ordina gli sort()
elementi come stringhe in ordine alfabetico e crescente.
Guarda anche:
Ordina la funzione di confronto
L'ordinamento alfabetico funziona bene per le stringhe ("Mela" viene prima di "Banana").
Tuttavia, l'ordinamento dei numeri può produrre risultati errati.
"25" è maggiore di "100", perché "2" è maggiore di "1".
Puoi risolvere questo problema fornendo una "funzione di confronto" (vedi esempi sotto).
Sintassi
array.sort(compareFunction)
Parametri
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). |
Valore di ritorno
L'array con gli elementi ordinati. |
Altri esempi
Ordina i numeri in ordine crescente:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Ordina i numeri in ordine decrescente:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
Trova il valore più basso:
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];
Trova il valore più alto:
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];
Trova il valore più alto:
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];
Supporto browser
sort()
è una funzione ECMAScript1 (ES1).
ES1 (JavaScript 1997) è completamente supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |