javascript function sort order in descending order [duplicate]

1

This javascript function sorts in ascending order How do I get her to sort out in order?

ordenaNomeCompleto: function(a,b){
    var ans = a.nome_completo.localeCompare(b.nome_completo);
    return ans;
}
    
asked by anonymous 08.07.2018 / 01:36

1 answer

3

To do the descending order simply change the order of the comparison, changing b to a in the comparison site:

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

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

Test:

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

Saving the result to a variable to return soon 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 return the value directly like this:

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

That's shorter and easier to read.

    
08.07.2018 / 02:05