Simon & Matt's new Photoshop book is out now!

Photoshop CS3 Layers Bible book cover

Sharpen your Photoshop skills today!

PageKits.com Featured PageKits

Artman PageKit
Artman ($24.99)


Clear Thinking PageKit
Clear Thinking ($44.99)


See more! > >

 

Tutorial: Sorting JavaScript arrays

Level: Intermediate. Published on 27 May 2008 in 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.

The end

That's the end of this article. We hope you found it useful. If you're still stuck and would like further help, check out our online Help Forums, where you can get assistance from members of Elated and other webmasters.

Also, don't forget the free ELATED Extra Newsletter, where you can get more great Web-building articles and tips sent straight to your inbox!

If you would like to offer us feedback on this or any of our articles, please contact us. Have fun!

Top of Page

Get our free newsletter!

  • Improve your Web skills
  • Exclusive tips and tricks
  • Free bonus Web template

Sign up now!

We won't give or sell your email address to anyone, and you can unsubscribe at any time. Privacy statement