# Filtering, sorting and grouping

> Pivot member, label and value filters (top and bottom N), member sort with locale collation and custom order, value sort, and number, date and custom grouping in the engine.

Canonical: https://salmonui.dev/docs/pivot-table/filtering-and-sorting

Filters live in `pivotModel.filterBy`, keyed by field. Each field takes one
filter of one of these shapes:

```ts
filterBy: {
  region: { include: ['Asia', 'Europe'] },                     // member filter
  country: { label: { operator: 'startsWith', value: 'G' } },  // label filter
  product: { value: { measure: 'amount', operator: 'top', value: 3 } }, // value filter
}
```

To clear a filter, remove its entry. The member editor builds member filters
(see [Member editor and filters](https://salmonui.dev/docs/pivot-table/filtering-ui)).

## Label filters

Label filters use the Data Grid operator names: `equal`, `notEqual`,
`contains`, `doesNotContain`, `startsWith`, `doesNotStartWith`, `endsWith`,
`doesNotEndWith`, `greaterThan`, `greaterThanOrEqual`, `lessThan`,
`lessThanOrEqual`, `between` and `notBetween` (`value2` is the upper bound).
How values compare depends on the field type:

- String members compare by their label, ignoring case unless you set
  `caseSensitive: true`.
- Number members compare numerically: `{ operator: 'greaterThan', value: 2024 }`.
- Date members compare as dates (before, after and between):
  `{ operator: 'between', value: '2024-03-01', value2: '2024-06-30' }`.

## Value filters

A value filter keeps the members of a row or column field whose total for
`measure` passes the condition. The total is taken against the other axis's
grand total. The operators are `equal`, `notEqual`, `greaterThan`,
`greaterThanOrEqual`, `lessThan`, `lessThanOrEqual`, `between`, `notBetween`,
and `top` / `bottom` with N in `value`. Top and bottom N apply within each
parent member. Filtered-out members are removed before aggregation, so
subtotals and grand totals cover only the members you see. `measure` is a
measure id or a calculated field name.

## Member sort

`pivotModel.sort[field]` is `'asc'` (the default), `'desc'`, `'none'` (data
order) or `{ order: [keys...] }`, which puts the listed members first and
sorts the rest ascending. Strings compare with
`Intl.Collator` for the engine `locale` with numeric collation, so `Item 2`
sorts before `Item 10` (alphanumeric sorting) and `ä` sorts as the locale
expects. Numbers and dates sort by value, and `(Blank)` comes first.

## Value sort

`<PivotTable valueSorting />` adds a sort button to each value column header: a click, or Enter / Space on the header
(Shift+Enter when the header also drills), cycles ascending, descending and
none, and fires the cancellable `onBeforeSortChange` and `onSortChange`.
`pivotModel.valueSort` orders row members by their values in one column:

```ts
valueSort: { columnKey: '["2025"]', measure: 'amount', direction: 'desc', multipleAxis: true }
```

`columnKey` is a column header key (with or without its `|measure` suffix).
`''` means the grand total column. Members without a value go last.
`multipleAxis: true` sorts every row level; without it only the innermost row
field is sorted, and the outer levels keep their member sort.

## Grouping

The engine maps grouped members to new members without copying any rows.
The grouping dialog lives in the React package (see
[Editors](https://salmonui.dev/docs/pivot-table/editors)).

- `{ kind: 'number', start, end, interval }` creates ranges named `0-199`.
  Values below `start` or above `end` go to `< start` and `> end`.
- `{ kind: 'date', parts: ['years', 'quarters', 'months'] }` splits a date
  field into nested levels named `date_years`, `date_quarters` and
  `date_months` (a single part keeps the field's own name). The parts are
  `years`, `quarters`, `quarterYear`, `months`, `days`, `hours`, `minutes`
  and `seconds`, all read in UTC so that server and client render the same
  members.
- `{ kind: 'custom', groups: [{ caption, members }] }` merges the listed
  members under one caption.

Filters, sort and paths use the grouped members: for example
`filterBy.date_years` or `['rows', 2024, 1]`.

## From code

The store has one cancellable command per part of the model; each fires its
specific events and `onBeforePivotModelChange` / `onPivotModelChange`
([State and events](https://salmonui.dev/docs/pivot-table/state)):

```ts
pivot.setFilter('country', { exclude: ['Japan'] }); // onBeforeFilterChange / onFilterChange
pivot.setSort('country', { order: ['Japan', 'India'] }); // onBeforeSortChange / onSortChange
pivot.setValueSort({ columnKey: '', measure: 'amount', direction: 'desc' }); // the same sort events
pivot.setGrouping('placed', { kind: 'date', parts: ['years', 'quarters'] }); // action: 'group'
pivot.setGrouping('placed', null); // ungroup
```

In the UI, the sort items of a field menu set the member sort, the value
column headers of `<PivotTable valueSorting>` set the value sort, and
"Group…" in the menu of a field on the rows or columns opens
the grouping dialog.

### Live demo: Sorting and grouping

Live demo: https://salmonui.dev/demos/pivot-table/pivot-table-sorting-grouping

Member sort ascending, descending, in data order or in a custom order, value sorting from the column headers, and date, number and custom grouping from code and the field menu.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { PivotAxisBar, PivotTable, usePivot, type PivotFieldDefinition, type PivotMemberSort, type PivotModelInput, type PivotValueSort } from '@salmonui/pivot-table';
import { Button } from '@salmonui/buttons/button';

type Order = { country: string; product: string; placed: string; price: number; amount: number };

const COUNTRIES = ['Brazil', 'Canada', 'France', 'Germany', 'India', 'Japan'];
const PRODUCTS = ['Bikes', 'Helmets', 'Gloves'];

/** 720 orders over 2025 and 2026; `placed` is an ISO date string (dates group in UTC). */
function makeOrders(): Order[] {
  const rows: Order[] = [];
  for (let n = 0; n < 720; n++) {
    const month = n % 24;
    const day = ((n * 7) % 27) + 1;
    const placed = `${2025 + Math.floor(month / 12)}-${String((month % 12) + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    const price = ((n * 53) % 480) + 20;
    rows.push({ country: COUNTRIES[(n * 5) % 6]!, product: PRODUCTS[(n * 11) % 3]!, placed, price, amount: price * ((n % 4) + 1) });
  }
  return rows;
}

const ORDERS = makeOrders();

const FIELDS: PivotFieldDefinition<Order>[] = [
  { field: 'country', caption: 'Country' },
  { field: 'product', caption: 'Product' },
  { field: 'placed', caption: 'Placed', type: 'date' },
  { field: 'price', caption: 'Unit price', type: 'number' },
  { field: 'amount', caption: 'Amount', type: 'number' },
];

const MODEL: PivotModelInput = {
  rows: [{ field: 'country' }, { field: 'product' }],
  columns: [{ field: 'placed' }],
  values: [{ field: 'amount', aggregate: 'sum' }],
  groups: { placed: { kind: 'date', parts: ['years', 'quarters'] } },
  formats: { amount: { number: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 } } },
};

const REGIONS = {
  kind: 'custom',
  groups: [
    { caption: 'Americas', members: ['Brazil', 'Canada'] },
    { caption: 'Europe', members: ['France', 'Germany'] },
    { caption: 'Asia', members: ['India', 'Japan'] },
  ],
} as const;

const describeSort = (sort: PivotMemberSort | null, valueSort: PivotValueSort | null): string =>
  valueSort ? `rows by ${valueSort.columnKey || 'grand total'} ${valueSort.direction}` : JSON.stringify(sort);

/** Member sort with a custom order, value sorting from the column headers, and number, date and custom grouping. */
export default function PivotTableSortingGroupingDemo() {
  const [last, setLast] = useState('none yet');
  const pivot = usePivot<Order>({
    data: ORDERS,
    fields: FIELDS,
    defaultPivotModel: MODEL,
    locale: 'en-US',
    onSortChange: (event) => setLast(`${event.field ?? 'value sort'}: ${describeSort(event.sort, event.valueSort)} (${event.source})`),
  });
  const sort = (value: PivotMemberSort) => pivot.setSort('country', value);
  const priceBands = () =>
    pivot.setModel((m) => ({ ...m, rows: [{ field: 'price' }], groups: { ...m.groups, price: { kind: 'number', start: 0, end: 399, interval: 100 } } }));
  const countries = () => pivot.setModel((m) => ({ ...m, rows: [{ field: 'country' }, { field: 'product' }] }));

  return (
    <div>
      <div className="demo-toolbar" role="group" aria-label="Member sort of Country">
        <span>Country order</span>
        <Button variant="outline" onClick={() => sort('asc')}>
          Ascending
        </Button>
        <Button variant="outline" onClick={() => sort('desc')}>
          Descending
        </Button>
        <Button variant="outline" onClick={() => sort({ order: ['Japan', 'India', 'Germany'] })}>
          Japan, India, Germany first
        </Button>
        <Button variant="outline" onClick={() => sort('none')}>
          Data order
        </Button>
        <Button variant="outline" onClick={() => pivot.setValueSort({ columnKey: '', measure: 'amount', direction: 'desc' })}>
          Rows by grand total
        </Button>
      </div>
      <div className="demo-toolbar" role="group" aria-label="Grouping">
        <span>Group</span>
        <Button variant="outline" onClick={() => pivot.setGrouping('placed', { kind: 'date', parts: ['years', 'quarters'] })}>
          Placed: years and quarters
        </Button>
        <Button variant="outline" onClick={() => pivot.setGrouping('placed', { kind: 'date', parts: ['months'] })}>
          Placed: months
        </Button>
        <Button variant="outline" onClick={() => pivot.setGrouping('country', REGIONS)}>
          Countries into regions
        </Button>
        <Button variant="outline" onClick={() => pivot.setGrouping('country', null)}>
          Ungroup countries
        </Button>
        <Button variant="outline" onClick={priceBands}>
          Rows: unit price bands of 100
        </Button>
        <Button variant="outline" onClick={countries}>
          Rows: country and product
        </Button>
      </div>
      <PivotAxisBar pivot={pivot} />
      <PivotTable pivot={pivot} valueSorting height={340} columnWidth={130} aria-label="Orders with sorting and grouping" />
      <p className="demo-status" aria-live="polite">
        Last sort: <code>{last}</code>
      </p>
    </div>
  );
}
```
