Search code examples
ag-gridag-grid-vue

Is there a way to sort grouped rows by the number of child rows? AG Grid


Example image with highighted number of leaf nodes

There is a similar question named How to sort by the row group count in ag grid? The anwser although marked correct, doesn't solve the issue.

It involves using custom sorting provided at a column level by configuring a comparator on the column definition. The issue is that the comparator compares leaf nodes and not parent grouped rows.

The comment section of the above answer suggests that using the "allChildrenCount" property can solve that (comparing the chidren count). But it doesn't, since the rows compared have the same parent and therefore same number of children.

Same issue exists as official closed ag-grid github issue. It suggest same answer.

I'm using vue 3 & ag-grid v29.0.0 (the example is in v28.0.2 but there was no difference conserning the issue) Example of the issue in codesandbox

I've tried using the 2 answers above which didn't solve the issue. I've also read the documentation on row-grouping and couldn't find anything useful.


Solution

  • Here are the pieces needed to make it work:

    const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
    
    const groupSortComparator = (params) => {
        if (params.nodeA && params.nodeB) {
            return collator.compare(params.nodeA.allChildrenCount, params.nodeB.allChildrenCount);
        }
        return 0;
    };
    
    this.gridOptions = {
        initialGroupOrderComparator: groupSortComparator,
        autoGroupColumnDef: {
            comparator: (valueA, valueB, nodeA, nodeB, isInverted) => {
                return groupSortComparator({nodeA, nodeB});
            },
        },
    };
    
    • Make sure gridOptions is being passed to the grid somehow.
    • You can use initialGroupOrderComparator (the default sort) or autoGroupColumnDef (for when the group column is sorted by the user), or both.
    • This code is for v29+, but can work in some earlier versions with slight adjustments.
    • You probably don't need Intl.Collator for this, but I didn't want to refactor.