Sorting JavaScript Arrays

Discover how to reverse the order of elements in an array; how to sort an array alphabetically; and how to sort an array in any order.

Previously we looked at the basics of JavaScript arrays, and showed how to manipulate the elements within them. In this tutorial, we take a look at how to sort array elements. You learn how to reverse the order of an array; how to sort an array alphabetically; and how to sort an array's elements into any order you like.

Reversing element order with reverse()

The reverse() method works much as you'd expect — it reverses the order of the elements in an array, so that the first element becomes the last, and the last becomes the first. Its syntax is simply:

array.reverse ( );

Note that it reverses the array itself, rather than returning a reversed copy of the array.

For example:

var fruits = [ "apple", "pear", "orange", "banana" ];
fruits.reverse ( );
alert ( fruits );  // displays "banana,orange,pear,apple"

Sorting array elements with sort()

You can sort the array elements in any order you like by using the sort() method. This has the following syntax:

array.sort ( compareFunction );

compareFunction lets you define a function to compare the array elements. We'll come to this shortly; however, you can miss out compareFunction entirely, in which case sort() sorts the array in ascending alphabetical order:

var fruits = [ "apple", "pear", "orange", "banana" ];
fruits.sort ( );
alert ( fruits );  // displays "apple,banana,orange,pear"

As with reverse(), sort() sorts the array in place, rather than returning a new, sorted array.

One important point here is that JavaScript converts each array element to a string, then sorts the elements alphabetically — or to be precise, lexicographically, like in a telephone book. This can produce some unexpected results when sorting arrays of numbers — for example:

var ages = [ 7, 105, 14 ];
ages.sort ( );
alert ( ages );  // displays "105,14,7"

What's going on here? Well, 105 starts with 10, which comes before 14 in lexicographical order. Furthermore, 14 starts with 1, which comes before 7.

Sorting in any order

If you want to sort your array elements in anything other than ascending alphabetical order, you need to supply your own comparison function. This is fairly straightforward; all your function has to do is take two arguments — a and b — compare them, and return a result as a number. The number your function returns determines whether or not a is "greater" than b in the sort order, as follows:

Your function returns a value less than 0
a is less than b; make sure a comes before b in the sorted array.
Your function returns a value greater than 0
a is greater than b; make sure a comes after b in the sorted array.
Your function returns exactly 0
a is the same as b; don't change the order of a and b in the sorted array.

A couple of examples make this clearer. First of all, let's sort our array of numbers in proper numeric order:

function compareNumbers ( a, b )
  if ( a < b )
    return -1;
  if ( a > b )
    return 1;
  return 0; // a == b

var ages = [ 7, 105, 14 ];
ages.sort ( compareNumbers );
alert ( ages );  // displays "7,14,105"

Next, let's try sorting our fruits array in order of string length, shortest first:

function compareStringLengths ( a, b )
  if ( a.length < b.length )
    return -1;
  if ( a.length > b.length )
    return 1;
  return 0; // a and b are the same length

var fruits = [ "apple", "pear", "orange", "banana" ];
fruits.sort ( compareStringLengths );
alert ( fruits );  // displays "pear,apple,orange,banana"

You can see that, with the help of comparison functions, sort() is a very powerful way to order your arrays.

Follow Elated

Related articles

Responses to this article

2 responses (oldest first):

11-Sep-09 17:43
why not just wrap your numbers with Number() before sorting?
12-Sep-09 10:47
@mrgccc3: You mean like this?

var ages = [ Number(7), Number(105), Number(14) ];
ages.sort ( );
alert ( ages ); // displays "105,14,7"

Makes no difference to the sort order - all Number() does is convert an object to a number, and they're already numbers in the first place.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page