6.11. Implementing a Custom Sort

Problem

You want to sort an array in a way such that the basic `sort( )` and `sortOn( )` methods do not suffice. You want to sort an array in a case-insensitive manner, perform a numeric sort, or use another custom or multikey criterion.

Solution

Use the `sort( )` method and pass it a reference to a `compare function`.

Discussion

If you want complete control over sorting criteria, use the `sort( )` method with a custom ```compare function``` (also called a ```sorter function```). The compare function is called repeatedly by the `sort( )` method to reorder two elements of the array at a time. The compare function receives two parameters (let’s call them a and b), which it should compare to determine which one should be ordered first. Your custom compare function should return a positive number, a negative number, or 0, depending on how the elements are to be sorted. If the function returns a negative number, a is ordered before b. If the function returns 0, then the current order is preserved. If the function returns a positive number, a is ordered after b. Your compare function is called with every relevant combination of elements until the entire array has been properly ordered. Using a custom compare function is easier than it sounds. You do not need to concern yourself with the details of the sorting algorithm; you simply specify the criteria for comparing any two elements.

Here is a simple compare function that performs a case-insensitive sort:

`function insensitiveSorter(a, ...`

Get Actionscript Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.