简体   繁体   中英

Datatables sorting - how to ignore text in column?

I have used this script to sort my datatable and ignore text that I do not want to sort, I'll explain.

this is the column example:

10,836
↑(10.71%)
14,836
↑(13.71%)

I want to ignore this: ↑(10.71%) and to sort according to this: 10,836.

thats my script:

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "justNum-pre": a => parseFloat(a.replace(/\D/g, "")),
  "justNum-asc": (a, b) => a - b,
  "justNum-desc": (a, b) => b - a
});
$(document).ready(function () {
  var table = $('#dataTable').DataTable({
      order: [[ 1, "desc" ]],
      scrollY: 200,
      scrollX: false,
      responsive: true,
      paging: false,
      //colReorder: true,
      //pageLength: 100,
      columns: [
          {
              "render": function(data, type, row){
                  return data.split(" ").join("<br/>");
              }
          },
          null,
          null,
          null,
          null,
          null,
          null
      ],
      columnDefs: [
      { className: "all", "targets": [ 0, 1, 3, 6 ] },
      {
        type: 'justNum',
        targets: 1
      }
      ]
  });
});

You can do this using the DataTables orderData feature.

For example, assume your formatted data is in the first column:

10,836
↑(10.71%)

Add a second column containing only the numeric portion (no text) 10836 and define it as a hidden column.

Then, create a columnDefs section in your datatable definition - something like this:

$('#demo').DataTable( {
    "columnDefs": [
      { "orderData": [ 1 ], "targets": 0 },
      { "visible": false, "targets": 1 }
    ]
  } );

} );

This says that the first column (target index 0) will use the data in the second column (target index 1) for sorting. And the second column will be a hidden column.

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