Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

javascript - DataTables sort mixed numeric and text column

I am trying to construct a DataTable sortable table that contains a column of numbers, but this column also contains the text NA to denote missing data. I was wondering how I would write a custom sorting function so that when I sort on the column the NAs come up AFTER the numbers rather than before when listing values greatest to smallest. Codepen here: https://codepen.io/mayagans/pen/VwKJeMo

$('#my-table').DataTable({
            "autoWidth": false,
            "order": []
        });
td {
  padding: 0 20px;
}

table {
  margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="my-table">
    <thead>
        <th>Nr. </th>
        <th>Name</th>
    </thead>
    <tr>
        <td>1</td>
        <td>Carl</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Alan</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Bobby</td>
    </tr>
      <tr>
        <td>NA</td>
        <td>Maya</td>
    </tr>
        <tr>
        <td>NA</td>
        <td>Jordan</td>
    </tr>
      </tr>
        <tr>
        <td>-</td>
        <td>Monica</td>
    </tr>
</table>
question from:https://stackoverflow.com/questions/65873263/datatables-sort-mixed-numeric-and-text-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can take advantage of orthogonal data, which lets you store a custom sorting value, which is different from the display value:

$('#my-table').DataTable( {
  columnDefs: [ { 
    targets: [ 0 ], 
    render: function ( data, type, row ) {
      if ( type === 'sort' ) {
        var sortValue = data;
        switch( data ) {
          case '-':
            sortValue = -999998;
            break;
          case 'NA':
            sortValue = -999999
            break;
          default: // already set, in this case
        } 
        return sortValue;
      } else { 
        return data;
      }
  }
  } ]
} );

This assumes you will never have numeric values lower than the two values used in the switch statement. You can adjust as needed, if your overall data is not compatible with this.

My sample:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...