简体   繁体   中英

Sorting Column in Given Order for dataTable

I have implemented dataTable and sorting data in order that I want. But I want to place the null values at last. And the records which actually has the value should be on top.

Example:

<tr>
    <td>D</td>
</tr>
<tr>
    <td>A</td>
</tr>
<tr>
    <td>Z</td>
</tr>
<tr>
    <td>-</td>
</tr>
<tr>
    <td>B</td>
</tr>
<tr>
    <td>-</td>
</tr>

And this one is my code for custom sorting:

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "alphbets-pre": function ( a ) {
        return jQuery.inArray( a, ["B","D","A","Z"] );
    },
    "alphbets-desc": function ( a, b ) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },
    "alphbets-asc": function ( a, b ) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

This one is working perfectly fine. Getting these results with the code:

ASC                 DESC
---------------     --------------- 
+ Alphabets  +      + Alphabates  +
---------------     ---------------
+ B          +      + -           +
---------------     ---------------
+ D          +      + -           +
---------------     ---------------
+ A          +      + Z           +
---------------     ---------------
+ Z          +      + A           +
---------------     ---------------
+ -          +      + D           +
---------------     ---------------
+ -          +      + B           +
---------------     ---------------

I want Sorting like:

ASC : B => D => A => Z => - => -
DESC: Z => A => D => B => - => -

Is there any solution to this?

Your $.inArray is returning -1 for "not-found" (or what you're calling "null" ( "-" )) so these appear at the top as they have the lowest integer value.

You can change this to something else, eg:

 "alphbets-pre": function ( a ) {
    var idx = jQuery.inArray( a, ["B","D","A","Z"] )
    return idx == -1 ? Number.MAX_SAFE_INTEGER : idx;
 },
function sortText(a, b, asc) {
    if ((!a || a === '-') && (!b || b === '-')) {
      return 0;
    }
    if (!a || a === '-') {
      return 1;
    }
    if (!b || b === '-') {
      return -1;
    }
    if (a > b) {
      return asc ? 1 : -1;
    }
    if (a < b) {
      return asc ? -1 : 1;
    }
    return 0;
  }

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