2

I am trying to find a way when using data tables to always sort empty cells to the top instead of the bottom.

I have found a few ways to always force empty cells to the bottom but am new with data tables and am not sure how to get it to sort the empty cells always to the top.

I am trying to find a way when using datatables to always sorty null/empty cells to the top instead of the bottom.

For example if my data was as follows

| ACCOUNT # |
|-----------|
|           |
| 035721576 |
|           |
| 035721577 |

It would sort it either

| ACCOUNT # |
|-----------|
|           |
|           |
| 035721576 |
| 035721577 |

or

| ACCOUNT # |
|-----------|
|           |
|           |
| 035721577 |
| 035721576 |
Robert E. McIntosh
  • 5,557
  • 4
  • 26
  • 35
  • I think this post refers to your problem: https://stackoverflow.com/questions/29829205/sort-an-array-so-that-null-values-always-come-last He wants the null fields at the bottom, but just change ascending to descentding. Hope this helps. – C4mps Dec 11 '18 at 14:09
  • Those force null to the bottom in both cases... I want to sort it so no matter what nulls are at the top. – Robert E. McIntosh Dec 11 '18 at 14:14

1 Answers1

2

You can create a sorting plugin that return a Number.*_INFINITY if the value is undefined, empty, null whatever (when a value evaluation return false):

var __emptyOnTop = function(a, b, high) {
  a = a || high;
  b = b || high;
  return ((a < b) ? -1 : ((a > b) ? 1 : 0));   
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
  "empty-on-top-asc": function (a, b) {
     return __emptyOnTop(a, b, Number.NEGATIVE_INFINITY)
  },
  "empty-on-top-desc": function (a, b) {
     return __emptyOnTop(a, b, Number.POSITIVE_INFINITY) * -1
  }
});

Usage

var table = $('#example').DataTable({
  columnDefs: [
    { targets: 0, type: 'empty-on-top' }
  ]
}) 

demo -> http://jsfiddle.net/y4ewqLmu/

In the future, when you have a problem like this, visit https://datatables.net/plug-ins/sorting/ and look for a similar use-case. I just grabbed the any-number plugin (by me, now part of the core) and made a few modifications.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265