Custom Sorting Function for JavaScript sort() Method Custom Sorting Function for Array.sort()

This tutorial extends our sort() method tutorial to introduce custom function arguments. The sort() method without arguments sorts array elements in an alpha-numerical way, based on the ASCII value of the character. JavaScript lets you define custom sort functions, which can be passed as argument to the sort() method to alter its sorting logic.

This tutorial explains how to write a custom function for the sort() method.

Creating a Custom Function for the sort() Method

A custom function for the sort() method must return an integer to let the sort() method know how to handle the two elements it iteratively passes to the custom function throughout the sorting process.

Possible return values for a custom sort function
Negative integer (<0)Sort the first argument before the second argument
Zero (0)Do not change the current sort order
Positive integer (>0)Sort the first argument after the second argument

The script below creates a custom sort function for the sort() method:

function customSort(a,b) {
    return( a.toString().length - b.toString().length );
}

var arlene = new Array("orange","apple","strawberry","banana");
alert( arlene.sort(customSort).toString() );

Let's explain our custom sort function customSort(): it substracts the string length (number of characters) of the second argument from first argument.

If the arguments "apple" and "strawberry" are respectively passed as a and b, the following will be returned: the number of characters in "apple" minus the number of characters in "strawberry" (5-10). The result return by customSort() is -5: "strawberry" should therefore be sorted after "apple".

Without regard for alphabetical order, the returned array's elements are sorted according word length (shorter words first). Custom sort function for JavaScript sort() method

As further illustration that a custom sort function completely overrides the native functionality of the sort() method, we have added letters to the first three fruits to give them the same word length. Notice that the JavaScript interpreter has left the elements in the order in which they appeared (no alphabetization), since the custom sort function returned zero (8-8=0). No alphabetical sorting for custom sort function

Test the Custom Sort Function

Interactively test our custom sort function by editing the JavaScript code below and clicking the Test Custom Sort Function button.

Browser support for JavaScript custom sort functions
Internet Explorer supports JavaScript custom sort functionsFirefox supports JavaScript custom sort functionsSafari supports JavaScript custom sort functionsOpera supports JavaScript custom sort functions