AKHIL NAMBIAR
AKHIL NAMBIAR

Reputation: 23

How to sort numbers in ag grid using comparator

I have been trying hours to solve the issue with sorting for the numeric values. It is sorting ascending correctly and descending correctly. If it has null it is not sorting correctly. Like if have 1,2,3,null for ascending it comes like 1,2,3,null.Here i need null at first position. For Descending it comes like 3,2,1,null which is correct.

Expecting for ascending null, 1,2,3,4. Actual it is 1,2,3,4,null

function nullsLastonSortNumber(val1, val2, node1, node2, isInverted) {

                            var isNullFirst = document.getElementById('{!$Component.pageId.oneValue}').innerHTML;


                            var currentSort= gridOptions.api.getSortModel();
                            if(isNullFirst=='false'){

                                if(currentSort[0].sort === 'asc'){

                                   if (val1 === null && val2 === null) {
                                    return 0;
                                     }
                                   if(val1 === null) {
                                    return -1;
                                    }

                                   if (val2 === null) {
                                    return 1;
                                     }
                                }
                                else if(currentSort[0].sort === 'desc'){
                                    if (val1 === null && val2 === null) 
                                    {
                                   return 0;
                                     }
                                    if (val1 === null) {
                                  return -1;
                                   }
                                  if (val2 === null) {
                                   return 1;
                                   }

                                }


                                return val1 - val2;

                            }                        

Upvotes: 0

Views: 3744

Answers (1)

pero_hero
pero_hero

Reputation: 3194

if you need ascending sorting with nulls first you could do something like:

var arr = [1,2,3,null];
arr.sort((a, b) => a-b);

this leads to [null, 1, 2, 3]

and for descending:

arr.sort((a, b) => b-a);

which leads to  [3, 2, 1, null]

accordingy you could rewrite your method to :

function nullsLastonSortNumber(val1, val2, nodeA, nodeB, isInverted) {
     val1 = val1 || -Number.MAX_VALUE;
     val2 = val2 || -Number.MAX_VALUE;

     var currentSort = gridOptions.api.getSortModel();
     if(currentSort[0].sort === 'desc'){                
           return val2 - val1 
     }
     return val1 - val2;
}

ag-grid custom comparator

Upvotes: 1

Related Questions