0

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]
1
  • 1
    I believe you didn't try searching it. There are so many resources talking about this. Commented Jul 31, 2012 at 8:56

6 Answers 6

4
//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;});
Sign up to request clarification or add additional context in comments.

5 Comments

original array : 1, 2, 3, 4, 5, ... 30.. after.sort and reverse() => 9,8,7,6,5,4,30,3,29,27,26,25,24...10,1
Notice that it's comparing the values lexicographically.
Yes just noticed this. Answer amended. Thanks.
Thanks, with the : sort(function(a, b) { return b-a }), it gives the right result.
@John - Cool. Sorry for initial mix up. I got excited that I knew this one and didn't fully think it over.
2

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

Comments

1

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

1 Comment

this would produce the array [50, 1000, 11, 8, 2, 0, 5], so not what he asked for. I think you're missing a call to sort, it should be myArray.sort().reverse()
1

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});

Comments

0

try this is simple :

 myArray.sort()

3 Comments

This would sort in ascending. He wants in descending order
do not use both sort and reverse. Either one of them
did you try this myArray.sort(function(a, b) { return b > a; });
0

This should do it:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.