uncategorized

Multi-Column Sort in Javascript

##The problem
Quite often one wants to sort a table or array by multiple attributes or columns. For example if we have an array of customers with the attributes name, age, profession, gender, city, state we may want to output the list by state, then city, then profession, then gender. On the server side if the data is in a database we would just use an ORDER BY in our query and be done. What, however, do we do if we want the sorting to be dynamic on the client side responding, for example, to user selection of column headers?

##The solution
We can use javascript’s built in sort function to do this. The sort function allows one to pass in a comparator function. The function is to “compare” the two objects and return -1 if b is less than a, 0 if b equals a, and +1 if a is greater than b.
The following comparator function will work for our case:

1
//aCust is an array of hashes. Each customer has the appropriate attributes
var param=["age","gender","profession","religion"];
var pl=param.length;
aCust.sort(function(a,b){
    for(var j=0;j<pl;j++){
        if (a[param[j]]<b[param[j]]) return -1;
        if (a[param[j]]>b[param[j]]) return 1;        
    }
    return a.name < b.name? -1:a.name>b.name?1:0;
});

The comparator loops through the parameters in order of precedence. If the first parameter of a is less than or greater than that of b we are done. If not we proceed to the next parameter and so on. We will only fall through to the final return if all the parameters are equal.
One can change the sort by changing parameter array dynamically. I will leave it as an exercise to modify the comparator function to sort some columns in descending rather than ascending order.
This is a very simple solution for sorting arrays dynamically. There is no need to make a server call and retrieve the data again in a different order. I have used this on a test list of 100K customers, sorting on 3 parameters and it takes about 0.5 seconds. Of course no one would expect to display 100,000 rows at one time, but it does illustrate that sorting should cause minimal delays.

Share