Sorting With a Custom Comparison Function

by Geethalakshmi 2010-09-16 21:22:02

Sorting With a Custom Comparison Function


Sorting is a common task. JavaScript provides a method for sorting arrays. However, the method sorts in alphabetical order by default. Non-string elements are converted to strings before sorting, which leads to unexpected results when working with numbers:

var list = [5, 10, 2, 1];
list.sort()
// list is now: [1, 10, 2, 5]


The explanation of this behavior is simple: Numbers are converted to strings before sorting them, so 10 becomes '10' and 2 becomes '2'. The JavaScript interpreter compares two strings by comparing the first two characters of each: str1 is considered "less than" str2 if str1's first character comes before str2's first character in the character set. In our case, '1' comes before '2' so '10' is less than '2'.

Fortunately, JavaScript provides a way to override this behavior by letting us supply a comparison function. This function defines how elements are sorted, it takes two compared elements a and b as parameters, and should return:

* A value less than zero if a < b.
* zero if a == b.
* A value greater than zero if a > b.

Programming such a function for number comparison is trivial:

function cmp(a, b) {
return a - b;
}


Now we can sort our array using this function:

var list = [5, 10, 2, 1];
list.sort(cmp);
// list is now: [1, 2, 5, 10]


This flexibility in Array.sort() allows for more sophisticated sorting. Let's say you have an array of forum posts, each post looks something like:

var post = {
id: 1,
author: '...',
title: '...',
body: '...'
}


If you want to sort the array by post id's, create the following comparison function:

function postCmp(a, b) {
return a.id - b.id;
}


It's reasonable to say that sorting using a native browser method is going to be more efficient than implementing a sort function in JavaScript. Of course, data should be sorted server-side if possible, so this shouldn't be used unless absolutely necessary (for example, when you want to offer more than one sort order on one page, and do the sorting in JavaScript).

Tagged in:

1034
like
0
dislike
0
mail
flag

You must LOGIN to add comments