2

I am trying to custom sort a grouped AG-Grid on the sport column based on a list SPORT_ORDER = [“Swimming”, “Gymnastics”, “Speed Skating”] but am unable to setup a comparator for it.

I am not sure if something is wrong with my comparator function or sorting like this not possible at all

If anyone can please help find out the issue with my comparator function and its use below, would be great.

import dash
from dash import html
import dash_ag_grid as dag
import pandas as pd, json

SPORT_ORDER = ["Swimming", "Gymnastics", "Speed Skating"]

_value_comparator = {
    "function": f"""
      function(a, b) {{
        const order = {json.dumps(SPORT_ORDER)};
        const ia = order.indexOf(a), ib = order.indexOf(b);
        if (ia < 0 && ib < 0) return 0;
        if (ia < 0) return 1;
        if (ib < 0) return -1;
        return ia - ib;
      }}
    """
}

df = pd.DataFrame({
    "athlete": ["Michael Phelps","Aleksey Nemov","Cindy Klassen",
                "Nastia Liukin","test","test2"],
    "sport":   ["Swimming","Speed Skating","Gymnastics",
                "Gymnastics","Swimming","Swimming"],
    "gold":    [8,2,1,1,2,3],
})

column_defs = [
    {
        "field": "sport",
        "rowGroup": True,
        "hide": True,
        "sortable": True,
        "sort": "asc",                 # triggers the comparator
        "comparator": _value_comparator,
    },
    {"field": "athlete", "minWidth": 150},
    {"field": "gold", "aggFunc": "sum", "width": 90},
]

auto_group_def = {
    "headerName": "Sport (custom order)",
    "cellRenderer": "agGroupCellRenderer",
    "cellRendererParams": {"suppressCount": True},
}

app = dash.Dash(__name__)
app.layout = html.Div(
    dag.AgGrid(
        rowData=df.to_dict("records"),
        columnDefs=column_defs,
        defaultColDef={"resizable": True, "filter": True},
        dashGridOptions={
            "groupDisplayType": "singleColumn",
            "rowGroupPanelShow": "always",
            "autoGroupColumnDef": auto_group_def,
        },
        enableEnterpriseModules=True,
        dangerously_allow_code=True,
        style={"height": 400, "width": 600},
    )
)

if __name__ == "__main__":
    app.run_server(debug=True)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.