简体   繁体   中英

Ag grid - How to sort column to show all null values as last?

I want to create a custom comparator to sort column asc/desc, but in both situations, I want to keep all empty (null) values at the end of the list

I use valueGetter to return a proper string value/null.

I think you can achieve this in 2 ways

First: use a comparator for the column you want to use custom sort

   columnDefs: [
        { 
            field: 'columnName', 
              comparator: (a, b, nodeA, nodeB, isInverted) => {
            if (a === b) {
                return 0;
              }
              // for null
             else if (a === 'null') {
                 return isInverted ?-1: 1;
             }
             else if (b === 'null') {
                 return isInverted ? 1: -1;
             }
             else { 
                return a.localeCompare(b);
             }

         }
}]
        
  1. a,b: The values in the cells to be compared. Typically sorts are done on these values only.
  2. nodeA, nodeB: The Row Nodes for the rows getting sorted. These can be used if more information, such as data from other columns, are needed for the comparison.
  3. isInverted: true for Ascending, false for Descending.

Second: use postSort mechanism, it will get called once everything is sorted

     <GridOptions> {
                  postSort:  this.postSort 
                  }// add this to grid options
          
 private postSort = function(rowNodes) {
    // null value data will be sorted at the end

    function checkNull(node) {
        return node.data.Id ===  null ; // if id is column is the one we are chceking
    }

    function move(toIndex, fromIndex) {
        rowNodes.splice(toIndex, 0, rowNodes.splice(fromIndex, 1)[0]);
    }

    var nextInsertPos = rowNodes.length; //last index

    for (var i = 0; i < rowNodes.length; i++) {
        if (rowNodes[i].data && checkNull(rowNodes[i])) {
            move(nextInsertPos, i)
            nextInsertPos++;
        }
    }
}

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