How to write custom Sorting in ag-grid?

JyotiChhetri picture JyotiChhetri · Mar 2, 2016 · Viewed 11.9k times · Source

I have a custom sorting function which sorts alphanumerically. I have set it to comparator as mentioned in ag-grid but, I dont find it working. Please put in some light.

var naturalSort = function(valueA, valueB, nodeA, nodeB, isInverted) {

      var NUMBER_GROUPS = /(-?\d*\.?\d+)/g;

      var aa = String(valueA).split(NUMBER_GROUPS),
        bb = String(valueB).split(NUMBER_GROUPS),
        min = Math.min(aa.length, bb.length);

      for (var i = 0; i < min; i++) {
        var x = parseFloat(aa[i]) || aa[i].toLowerCase(),
          y = parseFloat(bb[i]) || bb[i].toLowerCase();
        if (x < y) return -1;
        else if (x > y) return 1;
      }

      return 0;
    };

var columnDefs = [
    {headerName: "Name", field: "name", width: 110, comparator: naturalSort}

];


var gridOptions = {
    columnDefs: columnDefs,
    rowData: null,
    enableSorting: true
};

Answer

Carette picture Carette · Mar 31, 2017

As I tried to use the comparator function all the parameters showed as "undefined". There is no way of providing the values to compare or even node because as far as I could see naturalSort function is executed only once when rendering the grid.

For any alteration you need to do on sorting provide the full rowData to the natural sort function. Then for each row return the value you want the sorting to be used.

var columnDefs = [{
    field: "totalIncVat",
    headerName: translations.totalIncVAT,
    template: '<div title="{{data.totalIncVat | currency:\'&pound;\'}}"> {{data.totalIncVat | currency:\'&pound;\'}}</div>',
    comparator: naturalSort($scope.transactionsData)
}]

//componsate/reverse template alteration to actual field for correct sorting
var naturalSort = function(gridDataArray){
    _.forEach(gridDataArray, function(transaction){
        return gridDataArray.totalIncVat;
    });
};  

$scope.gridOptions = _.defaults({
    rowData: $scope.gridDataArray,
    columnDefs: columnDefs
});