Function javascript sorting in descending order

Asked

Viewed 1,282 times

1

This javascript function sorts in ascending order As I do for her to order in unbelieving order?

ordenaNomeCompleto: function(a,b){
    var ans = a.nome_completo.localeCompare(b.nome_completo);
    return ans;
}
  • This function does not sort strings, it only returns if one string,in terms of "value" of each character, is less, equal to or greater than another. If a is less than b, she will return -1. If a is equivalent to b, she will return 0. If b is greater than a, she will return 1. You should use these factors to perform the ordering

1 answer

3


To make the order decreasing just change the order of the comparison, changing the b for a at the place of comparison:

ordenaNomeCompleto: function(a,b){
    var ans = b.nome_completo.localeCompare(a.nome_completo);
    //        ^-----------------------------^
    return ans;
}

That works because by doing a.localeCompare(b), if the a is lower returns a negative value by positioning before b but if you do b.localeCompare(a) will already return positive in the same situation, positioning it this time at the end.

Testing:

const pessoas = [
  {nome_completo : "ana"},
  {nome_completo : "marcos"},
  {nome_completo : "carlos"},
  {nome_completo : "renan"},
  {nome_completo : "luis"}
];

const ordenaNomeCompleto = function(a,b){
    var ans = b.nome_completo.localeCompare(a.nome_completo); //a trocado com b
    return ans;
};

console.log(pessoas.sort(ordenaNomeCompleto));

Storing the result in a variable to return right away has no advantage unless it has a good name for a not very obvious value, which is not the case. For this reason it would be better to directly return the value like this:

ordenaNomeCompleto: function(a,b){
    return b.nome_completo.localeCompare(a.nome_completo);
}

That gets shorter and easier to read.

  • Thank you very much!!!!

Browser other questions tagged

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