简体   繁体   中英

Datatables Render Numeric Sort Issue

I am trying to use the following code and it will not sort the column correctly. The data is appearing correctly as integers but when I click on the column headers it appears to sort randomly.

{
  targets: 7,
  data: null,
  render: function(data, type, row, meta) {
    var value = Math.floor(Math.random() * Math.floor(100));
    if (type === "display") {
      return value;
    } else {
      return value;
    }

  }
},

This is caused by how DataTables handles orthogonal data - and how the random number generator in your render function is interfering with that process.

The Problem

In my test example, my table has 3 rows of data. I used column index 5, not 7. Here is my DataTable:

$(document).ready(function() {

  $('#example').DataTable( {

    columnDefs: [
      { targets: 5,
        render: function(data, type, row, meta) {
          var x = Math.floor(Math.random() * 100);
          console.log(type + ' - ' + x);
          return x;
        }
      } 
    ]

  } );
} );

The following output is logged to the console:

display - 97
display - 74
display - 39
type - 17
type - 19
type - 31
filter - 55
filter - 34
filter - 28

For each row of data, 3 different random numbers are generated - a display value, a type value and a filter value.

And the first time you sort on that column, another set of random numbers is generated:

sort - 4
sort - 12
sort - 85

It is these final values which are being used for sorting - and, of course they are likely to be a different sort order from the original display values.

A Solution

One solution is to capture the original display values in an array, and then use those values whenever a filter or sort value would otherwise be used:

$(document).ready(function() {

  var rands = [];

  $('#example').DataTable( {

    columnDefs: [
      { targets: 5,
        type: "num",
        render: function(data, type, row, meta) {
          var x = Math.floor(Math.random() * 100);
          if ( type === 'display' ) {
            rands.push(x);
            return x;
          } else {
            return rands[meta.row];
          }
        }
      } 
    ]

  } );
} );

Here we set up an array ( rands ) prior to declaring the DataTable. Then we populate that array with the display values when they are initially generated. We use the meta.row attribute to provide the relevant row index we need.

Then, when any other type of orthogonal data is encountered, we substitute the original display value from our array, to ensure consistent sorting (and filtering).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM