• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / JavaScript Arrays / Sorting JavaScript Arrays

Sorting JavaScript Arrays

27 May 2008 / 2 Comments

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.

Filed Under: JavaScript Arrays Tagged With: alphabetically, array, compare, comparison function, elements, lexicographically, order, reverse, sort()

Reader Interactions

Comments

  1. mrgccc3 says

    11 September 2009 at 5:43 pm

    why not just wrap your numbers with Number() before sorting?

    Reply
  2. matt says

    12 September 2009 at 10:47 am

    @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.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits