Web ScriptoPlanet()

# Custom Sorting Function for JavaScript sort() Method

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.

Negative integer (<0) Sort the first argument before the second argument Do not change the current sort order 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).

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

## 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