Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Craig Buckler, a freelance web developer from the UK and the lead technical writer at SitePoint.com who creates video tutorials for InfiniteSkills. Contact Craig at @craigbuckkler.

In this post, we’ll discuss how you can sort arrays in JavaScript. Sorting an array of values is a key development technique applied in a variety of situations.

Consider the following array of integers defined in a JavaScript array:

We can use the standard array `sort()` method to rearrange the values into logical order:

What result will be output?

The result may surprise you. Although you would expect [1, 2, 9, 15, 30], the actual output is a seemingly random [1, 15, 2, 30, 9].

The reason is logical once you understand how the `sort()` method operates. An array may contain numerous types of values: integers, real numbers, strings, objects and more. When the `sort()` method is used without a parameter, every value is converted to a string representation and sorted in lexicographic order. For example, “15” will come before “2” because the first character – “1” – is lower than “2”. Similarly, “Banana” will appear before “apple” because an uppercase “B” is lower than “a” in the character set.

## Comparison Functions

While string comparison has uses, it’s not the result we need. Fortunately, the array `sort()` method can be passed a comparison function as a parameter.

The comparison function expects two parameters – `a` and `b` – which are values from the array being sorted. The function must return a numeric value:

• If `a` is greater than `b`, the returned value must be positive (above zero).
• If `a` is smaller than `b`, the returned value must be negative (below zero).
• If `a` and `b` are equivalent, the returned value must be zero.

You can therefore define a function to sort an array of numbers from lowest to highest value:

This can be simplified, since subtracting `b` from `a` will also return a valid comparison value:

The `SortLowToHigh` comparison function can be passed to the array sort method:

Note: do not add `()` brackets after `SortLowToHigh`; we are providing a reference to that function rather than calling it.

The array is now sorted as we expect: [1, 2, 9, 15, 30].

## Inline Functions

If a comparison is used multiple times in your code, it’s practical to create a named function such as `SortLowToHigh` above.

Functions in JavaScript, however, are first-class objects and can be used like any other variable. Therefore, if we wanted to sort an array from the highest to lowest value, but only required it once in our code, we can pass an anonymous function to the `sort()` method:

## Sophisticated Sorting

The comparison function provides incredible flexibility, and we can sort arrays of variables or objects using any criteria. For example, we can define named map locations as objects in an array:

Sorting the map array by the object ‘`name`’ can be achieved using a comparison function that references the property:

Or we could sort locations by their shortest distance from any location. First, we’ll define a simple function that uses Pythagoras to calculate the distance between two co-ordinate objects:

This can then be used within a simple comparison function to determine the closest locations from ‘`home``(0, 0)`:

Alternatively, we could permit the user to enter any location in an HTML form:

We can then intercept their form submission and calculate the closest map point:

## Summary

At first glance, the array `sort()` method seems too simplistic for practical use. The comparison function, however, is powerful and permits sorting by any criteria. It’s just JavaScript code, so it can be as complex as you need. For instance, it could load external data using AJAX techniques, compare against geo-location co-ordinates, react to the browser window size, and so on.

Try writing `sort` comparison functions in your own projects. Further array lessons and exercises are available in my Learning JavaScript Programming video course.

Be sure to look at the JavaScript resources below that you can find in Safari Books Online.