TableFilter sort numeric column with empty values

In this example below you will see how to do a TableFilter sort numeric column with empty values with some HTML / CSS and Javascript

This demo shows how to implement a custom sorter handling empty, null or undefined values in a numeric column

Thumbnail
This awesome code was written by koalyptus, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright koalyptus ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>TableFilter sort numeric column with empty values</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link rel='stylesheet prefetch' href='https://koalyptus.github.io/TableFilter/tablefilter/style/tablefilter.css'>

  
  
</head>

<body>

    <table id="demo">
      <thead>
          <tr>
              <th>number</th>
          </tr>
      </thead>
      <tbody>
          <tr>
              <td>-144</td>
          </tr>
          <tr>
              <td>-20</td>
          </tr>
          <tr>
              <td></td>
          </tr>
          <tr>
              <td></td>
          </tr>
          <tr>
              <td>0</td>
          </tr>
          <tr>
              <td></td>
          </tr>
          <tr>
              <td></td>
          </tr>
          <tr>
              <td>1</td>
          </tr>
          <tr>
              <td>2</td>
          </tr>
          <tr>
              <td>3</td>
          </tr>
      </tbody>
  </table>
</body>
</html>
  <script src='https://unpkg.com/tablefilter@latest/dist/tablefilter/tablefilter.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/koalyptus/tablefilter-sort-numeric-column-with-empty-values-PjLVdO */
var filtersConfig = {
  base_path: 'https://unpkg.com/tablefilter@latest/dist/tablefilter/',
  col_types: ['number-or-empty'],
  extensions:[{
    name: 'sort',
    on_sort_loaded: function(tf, sort) {
      // sort.addSortType('number-or-empty', customCaster, customSorter);
    }
  }]
};

var tf = new TableFilter('demo', filtersConfig);
tf.init();

// Cast to number, handle empty, null or undefined values
function customCaster(val) {
  if(val === '' || val === null || val === undefined) {
    return -999999999;
  }
  return Number(val);
}

// Custom sorter
function customSorter(n1, n2) {
  if(n1.value < n2.value) {
    return -1;
  }
  if(n2.value < n1.value) {
    return 1;
  }
  return 0;
}

Comments