0

I already looked for answers to my question, for example Datatables sorting time column or Custom sort durations using jQuery DataTables but I have not been able to find one which suits my problem. Therefore, here I am.

I am using the jquery Datables : https://datatables.net/ to display tables in my current project. I got tables with columns containing durations such as :

99:39:25    
322:48:43
274:01:21
33:10:39

When I want to sort them out, the result is not correct :

99:39:25
33:10:39
322:48:43
274:01:21

I looked in the documentation for the sorting plug-ins (https://datatables.net/plug-ins/sorting/) but it did not help. I used the natural and time sorting and each time got the result above. Does anyone got an idea on how to proceed ?

This is what I am using to initialize the datatable in my HTML:

<script>
$(document).ready(function() {
 $('.dataresults').DataTable({
   "iDisplayLength": 25,
   "searching": true,
   "pagingType": "simple",
   "order": [[7, "desc"]],
   "columnDefs": [{
     "type": 'time', "targets": [6,7]
   }],
 });
});
</script>

1 Answer 1

0

I found the solution based on Custom sort durations using jQuery DataTables. I post the solution, if anyone would be in my case.

I replaced this regex:

/(?:(\d+)m)?\s*(?:(\d+)s)?/

by this one:

/(?:(\d+):)?(?:(\d+):)?(?:(\d+):)?/

and it is sorting as expected !

322:48:43
274:01:21
99:39:25
33:10:39

The full script becomes :

<script type="text/javascript">
$.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+):)?(?:(\d+):)?(?:(\d+):)?/);
        duration = parseInt(d[1] ? d[1] : 0) * 60 + parseInt(d[2] ? d[2] : 0) + parseInt(d[2] ? d[2] : 0) / 60;
    }
    return duration;
}
});

$(document).ready(function() {
$('.dataresults').DataTable({
  "iDisplayLength": 25,
  "searching": true,
  "pagingType": "simple",
  "order": [[7, "desc"]],
  "columnDefs": [{
    "type": 'duration', targets: [6,7]
  }],
});
});
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.