CancelImage Upload

Sorting a numeric array into a descending largest to smallest value order in JavaScript

In a previous tutorial I have discussed how a numeric array can be sorted with the elements being ordered from the smallest to largest value in JavaScript. However, what if we wanted to turn things around, and sort the numbers in the order from largest to smallest?

Here the sort function, sortBySize needs to be reversed so that the difference that is returned is not number1 minus number2, but instead number2 minus number1:

function sortBySize(number1, number2)
{

      return number2 - number1;

}

The rest is business as usual. By this I mean that the function sortBySize can be called upon via the object function sort():

var numbers = new Array('5', '15', '11', '349', '2', '79');

numbersSorted = numbers.sort(sortBySize);


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com