Check documentation for the latest version of dhtmlxSuite Sorting Data DHTMLX Docs

Sorting Data

The grid allows you to sort data rows on the client side (for server-side sorting, use the dhtmlxConnector library).

There are 2 ways to invoke sorting in the table:

  1. By a single click on the header of a column;
  2. By API call (can be called from some event or action, i.e. button click or page load).

Sorting by a single click on the header

When you click on the header, the grid starts displaying a special control indicating which column the grid is currently sorted by and the direction of this sorting (ascending or descending). Each next click on the same header will reverse the sorting direction.

Columns can have different type of content (numbers, strings, dates) and each type of content requires its own specific way of sorting.

There are 4 predefined sorting types:

  1. int
  2. date
  3. str (case-sensitive string)
  4. na - an unsorted column (the column won't react on the header click and the sortRows method)

To assign the desired types to columns and enable sorting for them, call the setColSorting method for the grid.

Sorting configuration

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");                
mygrid.setImagePath("./codebase/imgs/");       
mygrid.setHeader("Name, Email, Age"); 
mygrid.setColSorting("int,str,na,str"); mygrid.init();

Related sample:  Loading from JSON

Programmatic sorting

To invoke sorting on some event or action, i.e. on the button click or page load, use the sortRows method:

mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");                
mygrid.setImagePath("./codebase/imgs/");       
mygrid.setHeader("Name, Email, Age"); 
mygrid.init();
 
mygrid.sortRows(1,"str","asc"); //ascending sorting of the second column

Custom sorting function

If you need, you can specify your custom sorting type and apply it to a column. You should specify the related logic in a function and set this function for the required column in the setColSorting method:

The custom sorting function will be called for each pair of adjacent values, and it will return 1,-1 or 0:

  • 1 - an object with the first value in pair must go before the second one.
  • -1 - the second object goes before the first.
  • 0 - the order of both objects doesn't change.

Note, the length of the function name must be more than 5 symbols.

For example, if you want to sort some column by the number of symbols in the value, use the code as in:

Creating custom sorting type

function sort_custom(a,b,order){
    var n=a.length;
    var m=b.length;
    if(order=="asc")
        return n>m?1:-1;
    else
        return n<m?1:-1;
};
mygrid = new dhtmlXGridObject('gridbox');
mygrid.setSkin("dhx_skyblue");                
mygrid.setImagePath("./codebase/imgs/");       
mygrid.setHeader("Name, Email, Age"); 
mygrid.setColSorting("sort_custom,str,int");mygrid.init();

Related sample:  Custom sorting routine

Also, you can call the setCustomSorting method to assign a custom sorting function to a column:

function sort_custom(a,b,order){
    var n=a.length;
    var m=b.length;
    if(order=="asc")
        return n>m?1:-1;
    else
        return n<m?1:-1;
};
mygrid.setCustomSorting(sort_custom,1);

Related sample:  Custom sorting routine

Samples of custom sorting functions

Case-insensitive string sorting

dhtmlxGrid sorts strings in case-sensitive order by default, i.e. takes into consideration the letters' case. To make the sorting case-insensitive use the code as in:

function str_custom(a,b,order){ 
    return (a.toLowerCase()>b.toLowerCase()?1:-1)*(order=="asc"?1:-1);
};
 
mygrid.setCustomSorting(str_custom,1);

Date sorting

This sorting function can be applied to data of the format 'dd/mm/yyyy':

function date_custom(a,b,order){ 
    a=a.split("/")
    b=b.split("/")
    if (a[2]==b[2]){
        if (a[1]==b[1])
            return (a[0]>b[0]?1:-1)*(order=="asc"?1:-1);
        else
            return (a[1]>b[1]?1:-1)*(order=="asc"?1:-1);
    } else
        return (a[2]>b[2]?1:-1)*(order=="asc"?1:-1);
};
 
mygrid.setCustomSorting(date_custom,1);

Time sorting

This sorting function can be applied to data of the format '14:56':

function time_custom(a,b,order){ 
    a=a.split(":")
    b=a.split(":")
    if (a[0]==b[0])
        return (a[1]>b[1]?1:-1)*(order=="asc"?1:-1);
    else
        return (a[0]>b[0]?1:-1)*(order=="asc"?1:-1);
};
 
mygrid.setCustomSorting(time_custom,1);

Stable sorting

The default sorting routine used by Grid is a quick sorting algorithm which is unstable (it means that rows with the same value may change their position after sorting). To enable the stable sorting algorithm in the grid use the enableStableSorting method:

grid.enableStableSorting(true);

Basically, the stable sorting is a bit slower than the default one, so enable this mode only if it's really necessary.

Sorting by multiple columns

The sorting routine is designed to sort the grid by values of a single column by default.
But there are situations when you may need to sort the grid by multiple columns, for example, to sort books by the author at first, and then by the book's rating.

To sort the grid by multiple columns use one of the following techniques:

  1. The stable sorting. In this case the rows with the same values will not change their positions, and it will help to organize sorting by multiple columns:
    grid.enableStableSorting(true);
    grid.sortRows(1,"str","asc");    // sort by the sibling column
    grid.sortRows(0,"str","des");    // sort by the main column
    As a result, the grid will be sorted by a column of less importance and after that - by a column of higher importance. In combination with stable sorting it will give the same result as sorting by two columns.
  2. An extended version of the custom sorting function:
    function sort_by_two(a,b,order,aid,bid){
        if (a==b){
            var a2=grid.cells(aid,1).getValue();
            var b2=grid.cells(bid,1).getValue();
            if(order=="asc") { return a2>b2?1:-1; }
            else { return a2<b2?1:-1; }
        }
        if(order=="asc") { return a>b?1:-1; }
        else { return a<b?1:-1; }
    }
    where
    • a - 1st comparable value
    • b - 2nd comparable value
    • order - the sorting direction: "asc" or "des"
    • aid - the id of the row that contains the 1st comparable value
    • bid - the id of the row that contains the 2nd comparable value

Sorting events

dhtmlxGrid provides the onBeforeSorting event to add custom behaviour to default sorting.


For example, to implement server-side sorting without dhtmlxConnector or some other means you can use the onBeforeSorting event as in:

mygrid.attachEvent("onBeforeSorting",function(ind,type,direction){
    this.clearAll(); //clears grid
    this.load("some.url?dir="+dir+"&amp;ind="+ind);//loads new data from the server 
                                                      //in the required order
    this.setSortImgState(true,ind,direction); //sets a correct sorting image
    return false;   
});

Sorting combo's labels

dhtmlxGrid uses cells' values for sorting by default. To sort combo items by labels (which may differ from cell values), use a custom sorting function:

function custom_1(a,b,ord,a_id,b_id){
    a=mygrid2.cells(a_id,5).getText();
    b=mygrid2.cells(b_id,5).getText();
    return ord=="asc"?(a>b?1:-1):(a>b?-1:1);
};
 
mygrid.setCustomSorting(custom_1,5);
//5 - the index of the column that will be sorted

Partial sorting

To sort just a part of grid's rows and leave the remaming part fixed, use the following technique:

function custom_sort(a,b,ord,aid,bid) {
    var aid=aid.split("_");
    var bid=bid.split("_");
    if (aid[0]=="top") return 1;
    if (bid[0]=="top") return -1;
 
    return ((a>b)?1:-1)*(ord=="asc"?1:-1);
}

The above code moves rows with ID=“top_*” to the top of the grid and sorts other rows in the required order.

Back to top