Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 990
Dominik Avatar asked Sep 13 '25 12:09

Dominik


1 Answers

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++;
        }
    }
}
like image 72
Guruprasad mishra Avatar answered Sep 16 '25 01:09

Guruprasad mishra