Custom Sort Comparer

Custom Sort Comparer

danielku15danielku15 Posts: 6Questions: 1Answers: 0
edited May 2014 in DataTables 1.10

I want to have quite a special sorting for my rows. It's like a multi-column sorting which is invisible to the user. Let's assume I have this data:

data= [
{pinned: true, number: 1, value: 'Test 1'},
{pinned: false, number: 2, value: 'Test 2'},
{pinned: true, number: 3, value: 'Test 3'},
{pinned: false, number: 4, value: 'Test 4'},
{pinned: false, number: 5, value: 'Test 5'},
];

I always want to sort by pinned first, then sort by the column the user selected, then sort by number. This way I pin rows to the top of the table, then let the user sort it, and at the very end, the sequencial number of the items aren't scrabled:

[x] | 1 | Test 1
[x] | 3 | Test 3
[ ] | 2 | Test 2
[ ] | 4 | Test 4
[ ] | 5 | Test 5

My own comprarer would look like this:

var sortCols = [
    { field: 'pinned', asc: false }, // first sort by pinning
    { field: sort.col, asc: sort.dir }, // then by actual column
    { field: 'number', asc: sort.dir } // then by number
];
var comparer = function (a, b) { // where a and b are the full data, not only a single property/column
    // multicolumn sorting
    for (var i = 0, l = sortCols.length; i < l; i++) {
        var field = sortCols[i].field;
        var sign = sortCols[i].asc ? 1 : -1;
        var value1 = a[field], value2 = b[field];

        var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
        if (result != 0) {
            return result;
        }
    }
    return 0;
};

To achieve this I want to specify my very own comparer to sort my items. the _fnSort function uses a fixed multi-column comprarer. There's no possibility to do a custom sorting. I could try to override the _fnSort somehow but maybe there's a more built-in way of sorting the data on my own.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,489Questions: 1Answers: 10,470 Site admin
    Answer ✓

    Do you want the user to be able to modify the ordering at all? If not, then set up the multi-column order using the order option.

    If you do need the user to be able to adjust some aspect of the ordering, you can use the orderFixed option to tell DataTables want the prefix and postfix ordering should be.

    Allan

  • danielku15danielku15 Posts: 6Questions: 1Answers: 0

    Thanks for the DT orderFixed hint. Using this property I managed to create my sorting. By adjusting the CSS I also managed to hide the sort arrows for those fixed columns.

This discussion has been closed.