Explanation about the function and application of the javascript sort function

4

I know what the function below is for (return the candidate with the highest number of votes), but I do not understand the function of the function sort , passing another function.

Can anyone explain and / or where to find Portuguese material for this form of programming?

candidates = [
    {name: "Mr. Black", votes: 140},
    {name: "Mr. White", votes: 135},
    {name: "Mr. Pink", votes: 145},
    {name: "Mr. Brown", votes: 13}
];

var candidatesSorted = candidates.sort(function (a, b) {

    return b.votes - a.votes;
});
console.log(candidatesSorted[0]);
    
asked by anonymous 28.09.2018 / 23:33

3 answers

2
  

Array. prototype.sort ()

     

...

     

Syntax:

arr.sort([funcaoDeComparacao])
     

...

     

If the Parameter function is provided, the array will be sorted according to the return value of the Parse function. Considering that a and b are two elements being compared, then:

     
  • If Comparison function (a, b) is less than 0, it orders it to an index prior to b, i.e. a comes first.
  •   
  • If Comparison function (a, b) returns 0, leaves a and b unchanged relative to each other, but ordered relative to all other elements. Note: The ECMAscript standard does not guarantee this behavior, and therefore not all browsers (e.g. Mozilla versions prior to 2003) will respect this.
  •   
  • If Comparison function (a, b) is greater than 0, it orders b to an index earlier than a.   (a, b) must always return the same value given a specific pair of elements a and b as its two parameters. If inconsistent results are returned, then the ordering is undefined.
  •   

...

    
29.09.2018 / 00:07
2

Thinking about sorting in a generic way, there are several different algorithms, but one thing all have in common: in At some point, they need to compare two elements and decide which one will be put before and which one will be placed later (after all, "sort" is to put the elements in a certain order, following some sort order).

This is what the function passed to the sort method is for. It receives two parameters (in this case, a and b ), and decides whether, in the final result, a will be before or after b . This is set by return:

  • If a must be before b , the return must be a negative number (less than zero)
  • If a must be after b , the return must be a positive number (greater than zero)
  • If both the order is between them, the return must be zero

Seeing the function you used:

function (a, b) {
    return b.votes - a.votes;
}
Assuming a.votes is 140 and b.votes is 135, the function return will be -5 (a negative number). That is, in this case, a will be before b in the final result.

If a.votes is 13 and b.votes is 140, the function return will be 127 (a positive number). Then in this case, a will be after b in the final result.

And if the values of a.votes and b.votes are equal, the function returns zero, indicating that in this case both does the order between them.

In general, whenever a.votes is greater than b.votes , the result will be negative and a will be before b (elements with the largest values of votes will be before elements with values minors).

In other words, the end result is an array with the candidates in descending order of votes.

This function can have the logic you want, not just comparing a single field.

For example, let's assume that I want to sort the candidates in descending order of votes, but if they have the same number of votes, the tie-breaker is done in the alphabetical order of the name. The function would look like this:

// Mr. Black e Mr. Pink tem o mesmo número de votos
candidates = [
    {name: "Mr. Black", votes: 140},
    {name: "Mr. White", votes: 135},
    {name: "Mr. Pink", votes: 140},
    {name: "Mr. Brown", votes: 13}
];

var candidatesSorted = candidates.sort(function (a, b) {
    // primeiro verifica a ordem decrescente dos votos
    let result = b.votes - a.votes;

    // se os votos forem iguais, desempata pela ordem alfabética do nome
    if (result === 0) {
        result = a.name.localeCompare(b.name);
    }

    return result;
});

console.log(candidatesSorted[0]); // Mr. Black

To compare the names I used the localeCompare , which follows the same logic of returning -1, 0 or 1, using the alphabetical order as a criterion to define what comes before and after.

A site with documentation in Portuguese is the MDN (Mozilla Developers Network). The documentation for the sort function is here . p>

ps: Many pages are not completely translated, but at the top of the page, on the right side, it is possible to change the language (and I recommend English, as it does not have these translation problems).

    
29.09.2018 / 01:43
2

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"

    
29.09.2018 / 01:38