Sorting Arrays in JavaScript

The JavaScript array sort method rearranges the elements in the array it is invoked on and returns that array. If you don't provide a function argument to the sort method, the elements of the array will be sorted according to the order in the Unicode/UTF-8-character table. Depending upon the content of your array, this may not be the result you are expecting. Consider the following example:

var ar = ['apple', 'peach', 'Cherry', 'Pear', 'cantalope', 'Banana'];
// apply sort method to array and display result
console.log( ar.sort() );
// [ "Banana", "Cherry", "Pear", "apple", "cantalope", "peach" ]

Notice that all of the values that start with uppercase letters are sorted before any of the entries that begin with lowercase letters. Now let's see what happens with the default sort of numeric array values:

var ar = [37, 18.5, 22, 8, 4];
console.log( ar.sort() ); // [ 18.5, 22, 37, 4, 8 ]

As you can see from the above examples, we will generally need to pass a custom function to the sort method in order to achieve the desired results.

Defining Functions for the Array Sort Method

A function passed to the sort method should include two arguments to represent adjacent elements in the array to be sorted. If the first argument is to be sorted before the second, return -1 from the function. If the second argument is to be sorted before the first, return 1.[1] If the sort order doesn't matter, or the two values are equal, return 0.

The following demonstrates how to set up a case-insensitive sort:

var ar = ['ape', 'moose', 'Zebra', 'cow', 'Calf', 'Mountain Lion',  'goat'];

// invoke sort method on array, passing function inline 
console.log( ar.sort(function (a, b) {
    if ( a.toLowerCase() < b.toLowerCase() ) {
        return -1;
    } else if ( a.toLowerCase() > b.toLowerCase() ) {
        return 1;
    } else {
        return 0;
} ) );
// [ "ape", "Calf", "cow", "goat", "moose", "Mountain Lion", "Zebra" ]

In order to accomplish the case-insensitive sort, we compare the lowercase versions of the two arguments (a and b).

Next we demonstrate a numeric sort:

var ar = [37, 18.5, 22, 8, 4];
console.log( ar.sort(function (x, y) { return x - y; } ) );
// [ 4, 8, 18.5, 22, 37 ]

A descending numeric sort is equally simple to set up:

var ar = [37, 18.5, 22, 8, 4];
console.log( ar.sort(function (x, y) { return y - x; } ) );
// [ 37, 22, 18.5, 8, 4 ]

Back to top

  1. While it is handy to use -1 or 1 as return values, you can use any value less than or greater than 0 in their place. Notice that the functions used to demonstrate numeric sorts return the result of subtracting one value from the other. ^