最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

I want to create a custom parator 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 want to create a custom parator 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.

Share Improve this question asked Mar 3, 2021 at 12:13 DominikDominik 1,3451 gold badge18 silver badges28 bronze badges 1
  • 1 please let me know if you are facing any issue with the below answer. Thanks! – Guruprasad mishra Commented Mar 4, 2021 at 9:41
Add a ment  | 

1 Answer 1

Reset to default 9

I think you can achieve this in 2 ways

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

   columnDefs: [
        { 
            field: 'columnName', 
              parator: (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 pared. 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 parison.
  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++;
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论