Skip to content

Tree, grouping and aggregation ​

Use a tree when rows have parent and child relationships, such as an org chart or a folder list. Use grouping when you want rows that share a column value gathered together, such as sales by region. Both expand and collapse, and group rows can show aggregates such as totals.

Your dataUseOptions you need
Each row holds a parent idTreetree
No parents, but rows share a column valueGroupinggrouping
You need a total or average per groupAggregationcolumn aggregate, and summary if wanted

tree and grouping cannot be used on one grid. Passing both throws invalid-option.

Show data as a tree ​

The data is a flat rows array, not nested objects. Each row has a property that points at its parent's key, and top-level rows have null.

Live demo — drawn by the real renderer

Click ▸ in the Unit column, or focus it and press → and ←. Type "Back" in the box and only matching rows and their ancestors stay. The headcount and budget of each parent row are values we filled in ahead of time with the sum of its children.

ts
interface OrgUnit {
  id: number;
  parentId: number | null; // null for top level
  name: string;
  head: number;
  budget: number;
}

const options: GridOptions<OrgUnit> = {
  columns: [
    { id: 'name', title: 'Unit', width: 240 },
    { id: 'head', title: 'Headcount', kind: 'number', align: 'end' },
    { id: 'budget', title: 'Budget', kind: 'number', align: 'end' },
  ],
  rows,
  rowKey: 'id', // a tree needs rowKey so rows can point at their parents
  tree: { parentKey: 'parentId', column: 'name', expandDepth: 1 },
};

Tree options ​

OptionDefaultMeaning
parentKeyrequiredThe property that holds the parent's key, or (row) => key | null
columnfirst visibleThe column that gets indentation and the expand button
expandDepth1How many levels start expanded. 1 expands the top level so its children show. 'all' expands everything
filterKeep'ancestors'A filter keeps matching rows and their ancestors. 'subtree' also keeps descendants
hasChildrenactual childrenDecides whether to show an expand icon before children exist (a slot for lazy loading)
  • Sorting orders siblings among themselves. Parent and child relationships stay as they are.
  • If a child matches the filter, its parent stays visible. Those ancestor rows are left out of aggregates.
  • A row whose parent cannot be found (an orphan) or rows that point at each other (a cycle) are lifted to the top level, and one hierarchy-data notice is sent through the error event.

Tree sort scope ​

Since 1.3.4

tree.sortScope is available from 1.3.4.

By default sorting orders both parents and leaves among their siblings ('all'). With tree: { sortScope: 'leaves' } only siblings without children are sorted, and parent rows keep their place in the source order. Use it for a view that keeps folders fixed and sorts only the files.

Group rows ​

Put column ids in grouping.by and rows with the same value gather under a group row. The order you write is the order of levels. Group rows are derived from data rows, so a group with no members does not exist.

Live demo — drawn by the real renderer
ts
const options: GridOptions<Sale> = {
  columns: [
    { id: 'id', title: 'No.', aggregate: 'rowCount' },
    { id: 'region', title: 'Region' },
    { id: 'channel', title: 'Channel' },
    { id: 'product', title: 'Product' },
    { id: 'amount', title: 'Amount', kind: 'number', aggregate: 'sum' },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['region'], expandDepth: 1 },
  summary: true, // a total row at the bottom
};

// change or clear the grouping later
api.setGroupBy(['region', 'channel']);
api.setGroupBy([]);
OptionDefaultMeaning
byrequiredColumn ids, one per grouping level in order
columnfirst visibleThe column that gets the group label and expand button
expandDepth1How many levels start expanded
  • Groups appear in the order they first show up in the sorted data. A group for empty values goes last.
  • groupable: false on a column definition stops that column from being a grouping key.
  • setGroupBy clears individual expand and collapse choices.

Sort groups by their total ​

Since 1.2.0

grouping.sortByTotal is available since 1.2.0. In 1.1.0 groups follow the order in which they first appear in the sorted rows.

The samples below assume the columns and rows you built earlier and the api the grid returned. Sale is the row type.

Give sortByTotal a column and a direction to order the group rows by that column's group aggregate (a total, for example).

ts
const options: GridOptions<Sale> = {
  columns: [
    { id: 'team', title: 'Team' },
    { id: 'member', title: 'Member' },
    { id: 'sales', title: 'Sales', kind: 'number', aggregate: 'sum' },
  ],
  rows,
  rowKey: 'id',
  grouping: { by: ['team'], sortByTotal: { column: 'sales', direction: 'desc' } },
};

// Change the direction or turn it off by passing the option again
api.setOptions({ grouping: { by: ['team'], sortByTotal: { column: 'sales', direction: 'asc' } } });
api.setOptions({ grouping: { by: ['team'] } }); // off: order of first appearance
  • column must exist and have an aggregate. direction is 'desc' (default, largest first) or 'asc'. Anything else raises invalid-option and the state stays.
  • Only groups with the same parent are sorted against each other. With several grouping levels it applies at each level.
  • The value counts only rows that pass the filter. A group whose aggregate is not a number, or whose calculation failed, goes last whichever the direction. Equal values keep their old order.
  • Clicking the header of the same column sets the direction of the group order. Clearing the sort returns to the option's direction. Sorting another column's header changes only the row order inside groups.
  • Passing the option again keeps expanded groups expanded (when expandDepth is the same).

See the gallery example group-sort-by-total.

Total and average with aggregation ​

Set aggregate on a column definition and its value shows on group rows and on the total row. Only rows that pass the filter are counted. The aggregate of a tree parent can be read from getDisplayRow(i).aggregates, and tree.parentAggregates: true draws them on the parent rows. Without it, a parent row shows its own value.

AggregateMeaning
'sum'Sum
'avg'Average
'min', 'max'Smallest and largest value
'count'Number of rows that have a value
'rowCount'Number of rows, empty values included
a function(values, ctx) => value, your own rule

Use an object for more options.

ts
{
  id: 'amount',
  title: 'Amount',
  kind: 'number',
  aggregate: { fn: 'sum', precision: 0, parse: 'loose' },
  aggregateFormat: (value) => `Total ${Number(value).toLocaleString('en-US')}`,
}
OptionMeaning
precisionDecimal places. When set, values are scaled to integers before adding, so 0.1 + 0.2 has no rounding error
parse'strict' (default) accepts numbers only. 'loose' also accepts commas, ₩, a trailing 원 and full-width digits. A function parses by itself
includeSelfIn a tree, include the parent's own value in its aggregate (default: children only)
  • Build the displayed text with aggregateFormat. Without it, the column's formatValue is applied to the value alone.
  • A value that cannot be read as a number is skipped, and one aggregate-skipped notice goes through the error event. A number too large to keep its precision raises aggregate-inexact.
  • Turn on the total row with summary: true or summary: { position: 'top', label: 'Total' }. Read it with getSummary().
ts
api.getSummary(); // { id: 18, amount: 7992000 }

Use several total rows ​

Since 1.2.0

summary.rows is available since 1.2.0. In 1.1.0 there is one total row.

The samples below assume the columns and rows you built earlier and the api the grid returned.

List rows in summary.rows to get several total rows, such as a total and an average.

ts
const money = (value: unknown) => Number(value).toLocaleString('en-US');

const options = {
  columns: [
    { id: 'branch', title: 'Branch' },
    { id: 'm1', title: 'Jan', kind: 'number', aggregateFormat: money },
    { id: 'm2', title: 'Feb', kind: 'number', aggregateFormat: money },
  ],
  rows,
  rowKey: 'id',
  summary: {
    position: 'bottom',
    rows: [
      { id: 'sum', label: 'Total', aggregate: { m1: 'sum', m2: 'sum' } },
      { id: 'avg', label: 'Average', aggregate: { m1: 'avg', m2: 'avg' } },
    ],
  },
};

api.getSummary(); // { m1: 120, m2: 90 }  the values of the first row (the total), with 3 rows
api.getDisplayRow(3); // { kind: 'summary', scope: 'total', rowId: 'sum', label: 'Total', aggregates: { m1: 120, m2: 90 }, … }
  • Each row has an id (required, unique among the rows), a label and an aggregate. Without label it uses summary.label, and then the locale's default text ("Total").
  • Only the columns listed in aggregate are calculated; the other cells stay empty. A row without aggregate uses the aggregate of the column definitions.
  • With position: 'bottom' the rows go at the bottom in the listed order; with 'top' they go at the top in the same order.
  • Only rows that pass the filter are counted. With no data the rows stay and their values are null.
  • getSummary() returns only the first row's values. Read each row with rowId and aggregates from getDisplayRow(i).
  • An empty rows, an empty or repeated id, or an unknown aggregate function raises invalid-option before any option is applied.
  • Total rows are not selectable, editable or sortable. Several per-group subtotal rows are not supported yet.

See the gallery example footer-multi-rows.

To define summary cells yourself or move the subtotal label, see Summary row cells.

Block expanding and grouping before it happens ​

hooks.beforeExpand and hooks.beforeCollapse run before a tree or group opens or closes, and hooks.beforeGroup before the grouping changes. Return false to cancel. The rules are in the hooks table.

Expand motion ​

With motion: true (1.5.0), rows slide and the expand arrow turns when you expand or collapse a tree or group. It is off by default, so the output is the same as before. It is skipped while scrolling and when more than 60 rows change at once, and nothing moves with the reduced motion setting. See Turn on motion.

Expand and collapse from code ​

MethodEffect
expandRow(key), collapseRow(key), toggleRow(key)Expand, collapse or toggle one row. A leaf or unknown key throws invalid-option
isRowExpanded(key)Whether the row is expanded
expandAll(), collapseAll()Expand or collapse everything
expandToDepth(n)Expand levels 0 to n-1 and collapse the rest
revealRow(key)Expand every ancestor of the row. Use it before scrolling or focusing
getDisplayRow(i)The kind (data, group, summary or detail), level and aggregates of display line i

The expansionChanged event carries a reason ('toggle', 'bulk', 'reveal' or 'data') and the changed rowKeys. For expand-all and collapse-all (bulk), rowKeys is empty, so read the state with isRowExpanded. Changing the grouping fires groupingChanged.

ts
api.on('expansionChanged', ({ reason, rowKeys }) => {
  if (reason === 'toggle') localStorage.setItem('open', JSON.stringify(rowKeys));
});

Change the grouping one column at a time ​

setGroupBy replaces the whole list. To add, remove or move a single column, use these. The checks are the same as setGroupBy: an unknown column, a groupable: false column, a column already grouped, or use together with a tree or pagination is an invalid-option and nothing changes.

MethodEffect
addGroupBy(columnId, index?)Add a grouping column; without index it goes last
removeGroupBy(columnId)Remove a grouping column; nothing happens if it was not grouped
moveGroupBy(columnId, toIndex)Reorder the grouping; a column that is not grouped is an invalid-option
resetExpansion()Back to the expandDepth of the options (tree.expandDepth for a tree)

A change of the grouping fires groupingChanged once. Groups that keep the same values keep their expanded state. When the grid is already in its initial state, resetExpansion ends without an event.

Named aggregates ​

Register names with functions in the aggregates option and use the name in a column aggregate. They belong to this grid only; there is no global registry.

ts
createGrid(el, {
  aggregates: { range: (values) => Math.max(...values) - Math.min(...values) },
  columns: [{ id: 'pay', kind: 'number', aggregate: 'range' }],
  /* ... */
});

A value is a function, an options object ({ fn: 'sum', precision: 2 }) or a built-in name. Reusing a built-in name such as sum, or using a name you did not register, is an invalid-option. A throwing function does not stop the grid; it is reported through the error event.

Selection and keyboard ​

  • A group row's checkbox shows three states from its descendants: all, some, none. Clicking selects all descendants, or clears them if all were already selected. Rows hidden by a filter are not touched.
  • Selection stores data row keys only. Group and total lines cannot be selected. Collapsing does not clear a selection.
  • Ctrl+A and the header checkbox act on every data row that passes the filter, collapsed or not.
  • Selecting a tree parent does not select its children. They are independent.
KeyAction
→ (hierarchy column, collapsed row)Expand
← (hierarchy column, expanded row)Collapse. On a collapsed row or a leaf, move to the parent line
Enter (group line)Toggle expansion. On a data line, Enter starts editing
SpaceToggle selection on a data line, or its descendants on a group line

The hierarchy column is the one set by tree.column or grouping.column. In other columns, ← and → move between cells as usual. With a tree or grouping, the grid's role becomes treegrid, and each line exposes its level and expanded state.

Group panel and group display modes ​

With groupPanel on, a group panel appears above the header. Drop a header cell on it to group by that column, drag chips to reorder, or drag one out of the panel to ungroup. For touch and keyboard the column menu (columnMenu) gains "Group by this column" and "Remove grouping". Everything goes through addGroupBy, removeGroupBy and moveGroupBy, so the groupingChanged event and the checks match the API.

OptionDescription
groupPaneltrue or { message, height, removable }. message is the hint when empty, height the height in px (default 40), removable whether × and dragging out can ungroup (default true).
grouping.hideColumnsHides the grouped columns while they are grouped. Ungrouping brings them back, and columns the user hid stay hidden. The column definitions (getColumns()) do not change.
grouping.hideRowsShows rows in group order without group lines. Groups cannot be collapsed and subtotal lines stay.
grouping.mergedMerges the group column cells vertically per value and draws no group lines (it implies hideRows). A merge breaks when the value of an earlier group column changes. Group columns stay visible even with hideColumns.
  • Tab to a chip, move with Left and Right, reorder with Alt+Left or Alt+Right, remove with Delete. Each change is announced to screen readers.
  • A column with groupable: false cannot be dropped on the panel (a red outline shows).
  • The panel is part of the grid height and stays above the header when scrolling. groupPanel needs the hierarchy bundle (no grouping option is required).
  • It cannot be combined with paging (same as grouping).

Move rows in a tree ​

In a tree, moveRows(keys, { childOf: parentKey, index? }) moves rows under another parent (at index, or as the last child). before and after place rows under the same parent as the target row. indentRows and outdentRows change the level one step at a time.

  • The parent is changed by editing the field tree.parentKey points at, and the edit is tracked like updateRows (when that field is a column). With a function parentKey, moves that change the parent are refused; reordering within the same parent still works.
  • Sibling order follows the stored order. The expand state is kept.
  • For the full rules see Reorder rows.
  • To move by dragging, turn on rowDrag: { dropAsChild: true }. Dropping on the middle of a row makes a child (Drag rows to move them).

Group headers that stay pinned while scrolling ​

Since 1.6.0

The groupRows option is available from 1.6.0.

In a long grouped table it is easy to lose track of the group you are in. With groupRows: { sticky: true } the header row of the group you are looking at stays under the column header.

ts
grouping: { by: ['team', 'city'], expandDepth: 'all' },
groupRows: { sticky: true }, // default false
  • Nested groups stack outermost first. Up to 3 levels are pinned; with deeper nesting only the innermost 3 are.
  • A click on a pinned row collapses or expands the group like the original row. The pinned rows change when you reach the next group.
  • A pinned row is a copy with the same look. It is aria-hidden, so screen readers read only the original row. It follows row height changes and works with pinned columns, RTL and virtual scrolling.
  • Without grouping, or with hideRows hiding the group rows, nothing is pinned.

Try it in the gallery example Group headers that stay pinned while scrolling.

Group dates by year, quarter or month ​

Since 1.6.0

The column groupBy is available from 1.6.0.

Give a date (date), date-time (datetime) or month (month) column a groupBy and grouping by that column uses a unit such as year, quarter or month instead of the exact date value.

ts
columns: [
  { id: 'date', title: 'Order date', kind: 'date', groupBy: ['year', 'quarter', 'month'] },
],
grouping: { by: ['date'] }, // 2026 > Q4 > November
groupByHow it groupsGroup value (key)
omitted or 'value'one group per date value (as before)–
'year', 'quarter', 'month', 'week', 'day'that unit, one level2026, 2026-Q4, 2026-11, 2026-W47, 2026-11-24
['year', 'quarter', 'month']nested groups, coarse to finethe keys above, per level
  • List the array in the order year, quarter, month, day without repeats. 'week' is only allowed alone (ISO week, Monday first).
  • Groups are in chronological order. Rows with an empty or unreadable date gather in an empty group at the end of their parent.
  • Group names follow the page language (ko shows 2026년, 4분기, 11월; en shows 2026, Q4, November). A 'quarter', 'month' or 'week' without a year level above it carries the year, like 2026 Q4. Change the wording with messages.groupDateYear, groupDateQuarter and groupDateWeek.
  • The value of a group row (getDisplayRow) is the key string above. Aggregates such as sums and averages, subtotal rows and the group names in exports follow the same unit.
  • A groupBy other than 'value' on a column that is not date, datetime or month raises invalid-option.

Try the gallery examples Group dates by year > month and Group dates by quarter, week or day.

Change child rows from a group row ​

Since 1.6.0

groupRows.editable and editGroupRow are available from 1.6.0. They also need the editing bundle.

List column ids in groupRows.editable and a double-click on that cell of a group row sets the value on every child row of the group at once. The cell shows the column's own editor (text, select, date …).

ts
grouping: { by: ['team'] },
groupRows: { editable: ['level', 'note'] }, // true = every column that has an editor and no aggregate
  • The value goes through the edit path. For every child the grid first checks editability, beforeEdit and validation, and if any child fails nothing changes (the reason shows in the input and validationFailed is raised). If all pass, everything is written as one undo step.
  • A cell with an aggregate (aggregate) and a column without an editor cannot be edited (changing the group value in the label cell is grouping.editable).
  • From code use api.editGroupRow(groupKey, columnId, value). It returns true when written and false when blocked, and throws invalid-option for a column that is not allowed or a key that is not a group row.
  • Event groupRowEdited { groupKey, columnId, value, keys } and the cancelable hook beforeGroupRowEdit { groupKey, columnId, value, keys }.

Try the gallery example Change a whole group's value from its group row.

Show numbers as shares and ranks inside groups ​

Since 1.6.0

ColumnDef.showAs, exportShowAs and getShowAsValue are available from 1.6.0.

Give a number column showAs and its values show as shares or ranks inside a grouped table. Only the display changes; the value, sorting, editing and aggregates stay.

showAsData rowsAggregate cell of a group row
'value' (default)the valuethe aggregate
'percentOfGroup'% of the innermost group's sumthe aggregate
'percentOfTotal'% of the grand total in scopethe group sum as % of the grand total too
'rankInGroup'rank in the innermost group (largest is 1, ties share a rank)the aggregate
  • Percentages use the column's number format (format.number) with one decimal and %. Ranks are integers. An empty value leaves the cell empty.
  • Without grouping, or on a column that is not a number column, it has no effect (a non-'value' setting on a non-number column raises invalid-option).
  • api.getShowAsValue(rowKey, columnId) reads the displayed number (null when not applicable). The real value is getCellValue.
  • Export: by default the real value is exported. With exportShowAs: true the CSV and Excel exports of grouped rows contain the displayed value (percentage or rank number).

Try the gallery example Show numbers as shares and ranks inside groups.

Show groups as tree nodes ​

Since 1.6.0

groupMode is available from 1.6.0.

With groupMode: 'tree' groups are drawn as tree nodes in the first column: indent, toggle and guide lines, the group label in bold and the row count beside it in a lighter tone, like New York (12). Per-column aggregates stay in the cells of that row, and the arrow keys collapse and expand like a tree.

ts
grouping: { by: ['region', 'channel'], expandDepth: 1 },
groupMode: 'tree', // default 'flat'
  • The default 'flat' is as before (the label only, no count). Changing it does not change the grouping option, the API or the events.
  • It cannot be combined with the tree data option (parent key references): that raises invalid-option, as does any value other than 'flat' or 'tree'.
  • It works together with sticky group headers (groupRows.sticky), group row editing and showAs.

Switch between 'flat' and 'tree' in the gallery example Show groups as tree nodes.

Common pitfalls ​

Line numbers do not match the row count. Group and total lines take line numbers too. getVisibleRowCount() and rowIndex count display lines. To read data rows only, use getRowAtVisibleIndex(i), which returns undefined on group and total lines.

Collapsed rows are missing from getVisibleRows(). A collapsed row is not a visible row. Use getRows() when you need every row, collapsed ones included.

A tree parent shows no total. By default a parent shows its own value. Set tree: { parentAggregates: true } to show the total of its children in the aggregate columns (Subtotals, lazy loading, row heights and detail panels). Group lines and the total row only need aggregate. If values are strings, use parse: 'loose'.

I edited a parent value and the row disappeared. Editing the parentKey property or a grouping column moves the row to its new place the moment you commit. It can land under a collapsed parent.

I used tree and grouping together. That throws invalid-option. Use one of them.

A cellRenderer on the hierarchy column removed the expand button. Only the indentation is applied. The expand button is drawn by the default cell. Keep the default cell on the hierarchy column and use renderers on other columns.

Row numbers look odd with showRowNumbers. The line number is shown as is, so group and total lines are blank and data lines show their line number.

tree throws in the modular bundle. Tree, grouping and aggregation are the hierarchy bundle. Add features: [hierarchy] (Pick features).

Not available yet. Pivoting and dragging tree nodes. How to export trees and groups is in Export trees and groups. Subtotal rows, lazy loading, variable row heights and detail panels are covered in Subtotals, lazy loading, row heights and detail panels.