Skip to content

Sorting hierarchical data, misc suggestions #618

@Noino

Description

@Noino

Hi.

I was looking for a way to sort hierarchical data, kind of like cssChildRow, but a step further where rows have children, and those children can have children and so on ad infinitum.

Currently, I'm hacking away with a custom textSorter and parser, but this is by no means pretty. I've got one column i want to sort with, which contains a integer value. I want all rows to be sorted by this column, but i also want the parent child relationships to remain. Currently I'm writing a data-tablesort_parentid="" in to every child <tr>, linking it to its parent, and building a sortable value in the form of an array in my custom parser.

$.tablesorter.addParser({ 
    id: 'array_sortValue', 
    is: false,
    format: function(s, table, cell, cellIndex) { 
        var r = $(cell).closest('tr'),
            a = [];
        do {
            a.unshift(r.children(':nth-child('+ (cellIndex+1) +')').html());
        } while( (r = $('#'+r.data('tablesort_parentid'))).length );
        return a;
    }, 
    type: 'text' 
});

And sorting it with a custom sorter, starting from the most significant sort value at 0, and working onward from there, returning as soon as there's a difference.

textSorter: {
    3: function(a, b, direction, column, table) {
        for(var i=0,l=a.length; i<l; i++) {
            if (i in b) {
                if (parseInt(a[i]) === parseInt(b[i])) {
                    continue;
                }
                return parseInt(a[i]) < parseInt(b[i]) ? -1 : 1;
            } else {
                return 1;
            }
        }
        return b.length > l ? -1 : 0;
    }
}, 

I recognize that this approach fails to yield accurate results if two or more parents have the same sort value, but this is the best i could come up with short of modifying the library itself.

Anyway, enough of my use-case and ugly half functioning hacks. What i really came here for was to write up a few suggestions/feature requests that i consider useful or otherwise simply making things clearer/easier.

a) Rework sort function extension to match that of the parser. Took me an hour to find out that you can't add your own sorting type (which i expected to find), but you have to override text (for something that in this case really isn't text).

b) Please add "native" support (that actually works 100%) for hierarchys

c) Not really part of my initial problem, but i would do appreciate it when library's don't add useless markup, specifically referring to them div's in my thead>tr. ( found it: $.tablesorter.restoreHeaders, not the most elegant solution tho to have to call this on the next line after initializing)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions