John
John

Reputation: 7880

sorting an array by it's values

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

Answers (6)

SpaceBeers
SpaceBeers

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

magritte
magritte

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

ekholm
ekholm

Reputation: 2573

This should do it:

myarray.sort(function(a,b){return b - a})

Upvotes: 0

Matteo Tassinari
Matteo Tassinari

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

Xenione
Xenione

Reputation: 2213

try this is simple :

 myArray.sort()

Upvotes: 0

Anand
Anand

Reputation: 14915

Yes by using reverse method. Sort method would sort it in ascending order.

var myArray = [5, 0, 2, 8, 11, 1000, 50]; 

myArray.reverse();

For more operation on Array, look at this link

Upvotes: 1

Related Questions