Classificação de matriz JavaScript()
Exemplos
Ordenar matriz:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Classifique e inverta a ordem:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Definição e uso
O sort()
ordena os elementos de um array.
O sort()
sobrescreve a matriz original.
O sort()
classifica os elementos como strings em ordem alfabética e crescente.
Veja também:
Função de comparação de classificação
A classificação alfabética funciona bem para strings ("Apple" vem antes de "Banana").
Mas, classificar números pode produzir resultados incorretos.
"25" é maior que "100", porque "2" é maior que "1".
Você pode corrigir isso fornecendo uma "função de comparação" (veja os exemplos abaixo).
Sintaxe
array.sort(compareFunction)
Parâmetros
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). |
Valor de retorno
A matriz com os itens classificados. |
Mais exemplos
Classifique os números em ordem crescente:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Classifique os números em ordem decrescente:
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
Encontre o menor valor:
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];
Encontre o maior valor:
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];
Encontre o maior valor:
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];
Suporte ao navegador
sort()
é um recurso ECMAScript1 (ES1).
ES1 (JavaScript 1997) é totalmente suportado em todos os navegadores:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |