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

5

The sort function exists, but it sorts from the smallest to the largest, and I'd like to sort from highest to lowest. Is there any function in javascript for this?

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>
    
asked by anonymous 15.06.2014 / 16:37

1 answer

11

Use 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, it returns a negative value if a must appear before b , a positive value if it is the opposite, and 0 if both are equal or equivalent.

Reference:

15.06.2014 / 16:41