1
votes

I'm using the DataTables library, with hierarchical data. What I wish to do is to have the groups always appear in the same order, and have the column sorts apply only within groups.

For example, with the following table:

GROUP     FOOD
===================
fruit     banana
fruit     pear
fruit     apple
meat      steak
meat      chicken
meat      pork
vegetable zucchini
vegetable broccoli
vegetable tomato

When the user clicks the "food" column, it should sort ascending as follows:

GROUP     FOOD ▲
===================
fruit     apple
fruit     banana
fruit     pear
meat      chicken
meat      pork
meat      steak
vegetable broccoli
vegetable tomato
vegetable zucchini

When the user clicks the "food" column again, it should sort descending as follows:

GROUP     FOOD ▼
===================
fruit     pear
fruit     banana
fruit     apple
meat      steak
meat      pork
meat      chicken
vegetable zucchini
vegetable tomato
vegetable broccoli

However, the actual behavior is that it also inverts the ordering of the groups:

GROUP     FOOD ▼
===================
vegetable zucchini
vegetable tomato
vegetable broccoli
meat      steak
meat      pork
meat      chicken
fruit     pear
fruit     banana
fruit     apple

This example shows how to write a custom sort function; however, there's no way of knowing from within the function if the column is being sorted ASC or DESC. What is the best way to specify a different sort function for ASC vs. DESC order on a given column?

3
possible to get a fiddle? - Evan

3 Answers

0
votes

Usually with these types of tables you can specify a sorting function, and toggling the return value from 1 to -1 will change the sort. For example:

items.sort(function(a, b){
    if (a < b) { return 1; }
    else if (a === b) { return 0; }
    else { return -1; }
});

sorts in one direction, and

items.sort(function(a, b){
    if (a < b) { return -1; }
    else if (a === b) { return 0; }
    else { return 1; }
});

Sorts in the other.

0
votes

After a lot of digging, I managed to find the location of the current sort direction, under column.context[0].aaSorting[0][1]. The aaSorting variable is an array of arrays, the bottom level of which contains the current sort column (as an integer) and sort direction (as a string; asc or desc).

$.fn.dataTable.ext.order['grouped-item'] = function(settings, col){
    var column = this.api().column(col);
    var sortOrder = column.context[0].aaSorting[0][1];
    return column.data().sort(function(a,b){
        // ...
    }).map( function ( x, i ) {
        // ...
    } );
};
0
votes

Since my other answer is more in line with the original question, I'll leave it, but it turns out I was asking the wrong question. DataTables allows you to force sort by a particular column before sorting by others.