Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ag-grid: Count the number of rows for each filter choice

Tags:

ag-grid

In my ag-grid I want to display counts of rows next to each filter choice in a set filter, and maybe sort choices by that count (descending). This is what it looks like by default:

enter image description here

I want the choices to be displayed as

  • Select All (88)
  • Katie Taylor (2)
  • Darren Sutherland (1)
  • John Joe Nevin (1)
  • Barack Obama (0)
  • ...

What is the most efficient way to get those counts (and maybe sort the choices accordingly) from the row data, taking into account filters already set in the other fields (if any)?

like image 404
Stas Slabko Avatar asked Oct 24 '25 19:10

Stas Slabko


1 Answers

Assuming your columns field is "name", you could try building up a map and refer to this in the filters cellRenderer:

var nameValueToCount = {};
function updateNameValueCounts() {
    nameValueToCount = {};
    gridOptions.api.forEachNodeAfterFilter((node) => {
        if(!nameValueToCount.hasOwnProperty(node.data.name)) {
            nameValueToCount[node.data.name] = 1;
        } else {
            nameValueToCount[node.data.name] = nameValueToCount[node.data.name] + 1;
        }
    });
}

And your column def would look like this:

{
    headerName: "Name", 
    field: "name", 
    width: 120,
    filter: 'set',
    filterParams: {
        cellRenderer: NameFilterCellRenderer
    }
},

And finally, the NameFilterCellRenderer would look like this:

function NameFilterCellRenderer() {
}

NameFilterCellRenderer.prototype.init = function (params) {

    this.value = params.value;
    this.eGui = document.createElement('span');
    this.eGui.appendChild(document.createTextNode(this.value + " (" + nameValueToCount[params.value] + ")"));

};

NameFilterCellRenderer.prototype.getGui = function () {
    return this.eGui;
};

You would need to ensure that you called updateCountryCounts to update it when data changed (either with new/updated data, or when a filter was updated etc), but this should work for your usecase I think

like image 103
Sean Landsman Avatar answered Oct 27 '25 02:10

Sean Landsman