Two methods might be used to re-order items in an array; these are reverse() and sort() methods.

The reverse() method simply reverses the order of items in an array, as shown in this example:

var numbers = [1, 3, 5, 7, 9];

alert(numbers.reverse()); // 9,7,5,3,1

Sorting

The sort() method is more complex and offers more flexibility to a developer.

This method converts all items into strings (by applying String() function) and sorts them in ascending order, from the smallest to the largest value.

To achieve better control over the sorted items, the sort() method accepts a comparison function that is used to indicate in which kind of order the values will be sorted. Consider the following example:

var numbers = [5, 10, 15, 20];

alert(numbers.sort()); // 10,15,20,5

alert(numbers.sort(function(a,b) {return a-b}); // 5,10,15,20

In the example above we see that without a comparison function, all the numbers converted into strings get sorted out wrongly. To fix that problem, a function passed as an argument is allowed and it can be executed internally (as above), or evoked as a regular function outside the sort() method.

Example

The example with arrays re-ordering methods in JavaScript:

 

›› go to examples ››