Reputation: 7880
If I have an array like :
var myArray = [5, 0, 2, 8, 11, 1000, 50];
Can I sort it to get an array or numbers from the biggest number to the lowest one?, like this :
// [1000, 50, 11, 8, 5, 2, 0]
Upvotes: 0
Views: 86
Reputation: 13947
//Sort alphabetically and ascending:
var myArray = [5, 0, 2, 8, 11, 1000, 50];
myarray.sort();
//Sort alphabetically and descending:
var myArray = [5, 0, 2, 8, 11, 1000, 50];
myarray.sort();
myarray.reverse();
// Sort numerically decending order:
myArray = myArray.sort(function(a, b) {return b - a;});
Upvotes: 4
Reputation: 7636
You can use the sort()
function. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Note that the default behaviour of sort()
is alphabetically ascending. To sort in numerical descending order you will need to pass a compare function, e.g.
var myArray = [5, 0, 2, 8, 11, 1000, 50];
myArray.sort(function(a,b){return b-a});
Upvotes: 1
Reputation: 18584
you can try this:
var myArray = [5, 0, 2, 8, 11, 1000, 50];
myArray.sort(function(a, b) {
return b - a;
});
as suggested here: http://www.w3schools.com/jsref/jsref_sort.asp
Upvotes: 2