top of page

Efficient Row Group Sorting in AG Grid: A Simple Comparator Function

Updated: Mar 6

Hey folks,


Ever wanted to customize the sorting behaviour of row groups in AG Grid? Maybe you're using it to display data in your web application and want to order row groups based on the number of items they contain. Well, you're in luck! In this blog post, I'll show you how to create a custom comparator function in AG Grid to achieve exactly that.


The Challenge


AG Grid is a powerful JavaScript grid library that allows you to display and manipulate tabular data in your web applications. It provides various features for sorting and grouping data, including the ability to group rows based on certain criteria. However, by default, AG Grid sorts row groups alphabetically. But what if you want to sort them based on the number of items they contain? That's where a custom comparator function comes in handy.


The Solution


To create a custom comparator function in AG Grid for sorting row groups by the number of items, we need to follow these steps:

  1. Define the Comparator Function: First, we define a custom comparator function that compares the number of items in each group.

  2. Access Row Group Data: We access the row group data to calculate the count of items in each group.

  3. Compare Counts: We compare the counts of items in each group and return the appropriate result for sorting.

Example Code

Let's dive into some code to see how it works:


function groupCountComparator(a, b) {
    if (a === undefined || b === undefined)
    {
        return 0;
    }
    const countA = gridApi.rowModel.rowsToDisplay.find(x => x.key == a).allLeafChildren.length;
    const countB = gridApi.rowModel.rowsToDisplay.find(x => x.key == b).allLeafChildren.length;

    // Compare the counts and return the result
    if (countA < countB) {
        return -1;
    } else if (countA > countB) {
        return 1;
    } else {
        return 0;
    }
}

In this example, groupCountComparator function retrieves the count of items in each row group using gridApi.rowModel.rowsToDisplay, and then compares these counts to determine the sorting order.


Conclusion


By creating a custom comparator function in AG Grid, you can easily sort row groups based on the number of items they contain. This allows for more flexibility in displaying and organizing your tabular data.

I hope you found this blog post helpful! Feel free to leave a comment if you have any questions or suggestions.



Happy coding!

27 views0 comments

Comments


I'm a lead software developer currently working at AG Grid in London.

Technologies I'm currently focused on include Salesforce, .NET Core, Angular, SQL, React and Azure.

Other than that, in my spare time I watch the Arsenal at the Emirates, work on side projects or watch sports. Oh, and I'm also a part-time body builder.

You can contact me at vh@viqas.co.uk

profile.jpg

About Viqas Hussain

bottom of page