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;
}
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;
}
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 javascript
You are not signed in. Login or sign up in order to post.
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. Ifa
is less thanb
, she will return-1
. Ifa
is equivalent tob
, she will return0
. Ifb
is greater thana
, she will return1
. You should use these factors to perform the ordering– reisdev