Sort() sorts the elements of an array. This sort is according to the Unicode code table.
Syntax arr.sort([funcaoComparar])
If funcaoComparar
is not informed, the elements will be ordered according to their conversion to text.
Example: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sort()
outworking [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 it is about sorting by numbers
When the parameter funcaoComparar
is informed, the array will be ordered according to its return value.
Types of return:
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 their position according to this comparison, then it takes two values again and compares them to rearrange them again, and does so until the whole array is sorted.
Taking the example above, where we use a - b, the sort happens as follows: if the first element compared, in case a, is greater than b, 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, i.e., makes the sort 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 for descending ordering, b - a, but now with the values changed from place makes the ordering contrary to the previous one
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"
Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).
– Sorack