Custom sort durations using jQuery DataTables

2019-07-08 20:11发布

I need to sort a column in jQuery DataTables. I tried using the moment plugin without success.

The column contains call duration but it's not always there so we use N/A for those. Column data looks like:

2m 45s
1m 32s
N/A
45s
1m

I need to be able to sort these with the N/A valuing less than 0 and the rest to be in the logical order

I use jQuery DataTables 1.10.6, moment 2.9.0 and I do have all the datatables plugins. I use data-stype is th in the header of my table. I also use the no config datatable init looks like that

// Create DataTables User
    table = $('#summary-table').DataTable({
        'language'  : { "url": paths.lang_{{LaravelLocalization::getCurrentLocale()}} },
        'responsive':
        {
            'details':
            {
                'type': 'inline'
            }
        },
        'order': [[(nbCat + 5), 'desc']],
        'dom': '<"row"<"col-sm-12 before-table
               "<"table_controls">>r><"row"<"col-sm-12"t>><"row"<"col-sm-12"ipl>>',
        'lengthMenu': [[20, 50, 100, -1], [20, 50, 100, transAll]],
    });

1条回答
We Are One
2楼-- · 2019-07-08 20:40

SOLUTION

Use the code below:

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "duration-pre": function (s) {        
        var duration;

        s = s.toLowerCase();

        if(s === 'n/a'){ 
            duration = -1;

        } else {            
            d = s.match(/(?:(\d+)m)?\s*(?:(\d+)s)?/);
            duration = parseInt(d[1] ? d[1] : 0) * 60 + parseInt(d[2] ? d[2] : 0);
        }

        return duration;
    }
});

$(document).ready(function (){
    var table = $('#summary-table').DataTable({
       columnDefs: [
           { targets: 0, type: 'duration' }
       ]         
    });
});

Change 0 in targets: 0 to index of the column containing the duration. I omitted other table options for the sake of simplicity.

DEMO

See this jsFiddle for code and demonstration.

查看更多
登录 后发表回答