How to sort an array of numbers from largest to smallest?

Asked

Viewed 5,108 times

6

There is the function sort, but it sort from minor to major, and I’d like to sort from major to minor. There’s some function in javascript for that?

Code with sort:

var numeros = [200,100,400,900,600,700];
numeros.sort();
for(i = 0 ; i <  numeros.length; i++){
    $("ul#ul-numeros").append('<li>' + numeros[i] + '</li>');
}

<ul id="ul-numeros">
</ul>

1 answer

12


Use like this:

var numeros = [200,100,400,900,600,700];
numeros.sort(); // aqui ele vai ordernar do menor para o maior
numeros.reverse(); // aqui ele vai inverter as posições fazendo o efeito desejado

Example: Jsfiddle

Or

var numeros = [200,100,400,900,600,700];
numeros.sort(function(a, b){
    return b - a;
});

Example: Jsfiddle

Explanation Sort

When comparing two elements, returns a negative value if a should appear before b, a positive value if otherwise, and 0 if both are equal or equivalent.

Reference:

  • 1

    Thank you very much ...

  • 2

    +1. As a complement, it may be useful to clarify, for those who do not know, how the method parameter sort works (i.e. when comparing two elements, returns a negative value if a should appear before b, a positive value if otherwise, and 0 if both are equal or equivalent).

  • 2

    @mgibsonbr edited and put your explanation, thank you!

Browser other questions tagged

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