Sort () sorts the elements of an array. This sort is according to the unicode code table.
Syntax arr.sort([funcaoComparar])
If funcaoComparar
is not entered, the elements will be sorted according to their conversion to text.
Example: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sort()
result [1, 10, 2, 3, 4, 5, 6, 7, 8, 9]
"10" came before "2" because "1", which is the first character of "10", comes before "2"
In your case this is sort by numbers
When the funcaoComparar
parameter is entered, the array will be sorted according to its return value.
-
Return types:
se a comparação for menor que zero, a é posicionado antes de b
se a comparação for maior que zero, a é posicionado depois de b
se a comparação for igual a zero, a e b permanecem com as posições inalteradas
Example
var arr = [5, 3, 1, 4, 2];
console.log('Array original:', arr);
arr.sort(function(a, b) {
return a - b;
});
console.log('Array ordenado:', arr);
What happens is that sort () takes the original array, compares two values, and changes them according to that comparison, then it picks up two values again and compares them to rearrange them again, and do this until the entire array is sorted.
Taking the example above, where we use a - b, sorting happens as follows: if the first compared element in case a is greater than b, the subtraction a - b results in a value greater than zero, then a is positioned after b (according to the rules). This same logic applied repeatedly in the array, which is being modified, causes the larger values to be positioned further to the end of the array, ie, sorting in ascending order!
var arr = [5, 3, 1, 4, 2];
compare(5,3); // retorna 2, 3 é posicionado na frente de 5
[3, 5, 1, 4, 2]
compare(3,1) // retorna 2, 1 é posicionado na frente de 3
[1, 3, 5, 4, 2]
compare(1,4) // retorna -3, nada muda
compare(1,2) // retorna -1, 3, nada muda
compare(3,5) retorna -2 e compare(3,4) retorna -1 nada muda
compare(3,2) // retorna 1, 2 na frente de 3
[1, 2, 3, 5, 4]
compare(5,4) // retorna 1, 4 na frente de 5
[1, 2, 3, 4, 5]
The same logic applies to decreasing ordering, b - a, but now with the values changed place causes the ordering to be unlike the previous
Example
var arr = [5, 3, 1, 4, 2];
console.log('Array original:', arr);
arr.sort(function(a, b) {
return b - a;
});
console.log('Array ordenado:', arr);
more about "How the sort () method works"