Explanation of the function and application of the javascript Sort function

Asked

Viewed 801 times

4

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

Does anyone know how to explain and/or where to find material in Portuguese 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]);

  • 1

    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).

3 answers

3

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"

3

Thinking of ordering in a generic way, there are several different algorithms (each one with its particularities), but one thing they all have in common: at some point, they need to compare two elements and decide which will be put before and which will be put after (after all, "sort" is to put the elements in a certain order, following some sort of ordering rule).

That’s what the function passed to the method is for sort. It takes two parameters (in this case, a and b), and decides whether, in the final result (in the ordered array), a will be before or after b. This is defined by the return of this function:

  • if a must be before b, 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 it makes the order between them, the return should be zero

Seeing the function you used:

function (a, b) {
    return b.votes - a.votes;
}

Supposing 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 for 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.

What if the values of a.votes and b.votes are equal, the function returns zero, indicating that in this case either 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 (the elements with the highest values of votes will be before the elements with lower values).

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


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

For example, let’s suppose that I want to sort the candidates in the descending order of votes, but if they have the same number of votes, the tie-breaker is done alphabetically by 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 function localeCompare, which follows the same logic of returning -1, 0 or 1, using alphabetic order as a criterion to define what comes before and after.


One site that has documentation in Portuguese is MDN (Mozilla Developers Network). The function documentation sort is here.

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, since it does not have these translation problems).

2

Array.prototype.Sort()

...

Syntax:

arr.sort([funcaoDeComparacao])

...

If the Deparacao function parameter is provided, the array will be ordered according to the function’s return value. Whereas a and b are two elements being compared, then:

  • If functionDeparacode(a, b) is less than 0, sort a to an index earlier than b, i.e. a comes first.
  • If functionDeparacao(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 functionDeparacao(a, b) is greater than 0, sorts b to an index earlier than a. function Command(a, b) should 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.

...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.