Question on handling nulls on aaSorting

Question on handling nulls on aaSorting

rmaitipermaitipe Posts: 9Questions: 3Answers: 0
edited September 2016 in Free community support

I have web page where I'm displaying data that has a date column that is derived from the application and not from the database. The initial sort aaSorting is exactly whats needed as users want the data to be sorted by this date when visiting the page for the 1st time. However sorting causes the nulls to display at the very beginning of the list when in my case I want them at the end of the list. Is this something possible with the aaSorting or do I need to look into using a custom sort?

Here is my code.
$('#admitTbl').dataTable( {
"bSortable": true,
"aaSorting": [[2,'asc']],
...

Hi allan --
I created this JSfiddle to replicate the behavior.
https://jsfiddle.net/k4pmL8j0/1/

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,815Questions: 1Answers: 10,517 Site admin

    Could you give me a link to the page please? They should be sorted to the bottom I think, so it is possible there is an error there.

    Allan

  • rmaitipermaitipe Posts: 9Questions: 3Answers: 0
    edited September 2016

    I created this JSfiddle to replicate the behavior.

    https://jsfiddle.net/k4pmL8j0/1/

  • allanallan Posts: 63,815Questions: 1Answers: 10,517 Site admin

    Thanks. I'll look into this and get back to you.

    Allan

  • rmaitipermaitipe Posts: 9Questions: 3Answers: 0

    I've updated the initial fiddle because it was treating the dates as Strings. Please find the latest version here.
    https://jsfiddle.net/k4pmL8j0/4/

  • allanallan Posts: 63,815Questions: 1Answers: 10,517 Site admin
    Answer ✓

    Okay - I see the issue thanks. I don't believe that this is a bug in DataTables, but rather that you just don't want the default behaviour. When DataTables is sorting a date column and it finds something it can't parse as a date (i.e. an empty string in this case) it uses -Infinity as the value. That is why the two empty rows come before 10/10/2008.

    You have two options:

    1. Replace the default behaviour with what you want
    2. Use a custom plug-in that will behave as you want.

    The first is probably easiest:

    $.fn.dataTable.ext.type.order['date-pre'] = function ( d ) {
      return Date.parse( d ) || Infinity;
    }
    

    That isn't something I will change in DataTables - its current behaviour is correct for what I would expect (empty values should be -Infinity).

    Allan

  • rmaitipermaitipe Posts: 9Questions: 3Answers: 0

    Thanks Allan! I went with your first suggestion to override the default behavior and got it to work as desired.

This discussion has been closed.