# Sorting

> Sort by one or many columns from the header or from code, with type-aware comparison and custom comparators.

Every column is sortable unless you set `sortable: false`. Clicking a header cycles through ascending, descending and unsorted. The grid compares raw values according to the column type, so numbers, dates and booleans sort correctly even when they are formatted for display.

**Live demo: Sorting, floating filters and quick filter** (runs on the HTML version of this page). Source of `demos/sorting-filtering.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import {
  docsTheme,
  field,
  formatCurrency,
  layout,
  makeOrders,
  onDocsThemeChange,
  revenueOf,
  type Order,
} from './_shared';

export const meta = { title: 'Sorting, floating filters and quick filter', height: 480 };

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 110 },
  { field: 'customer', header: 'Customer', flex: 1, minWidth: 150 },
  { field: 'region', header: 'Region', width: 130, filter: 'set' },
  { field: 'status', header: 'Status', width: 116, filter: 'set' },
  { id: 'revenue', header: 'Revenue', type: 'number', width: 120, valueGetter: revenueOf, format: formatCurrency },
  { field: 'orderDate', header: 'Ordered', type: 'date', width: 120 },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const search = document.createElement('input');
  search.type = 'search';
  search.placeholder = 'Customer, product, rep…';
  toolbar.append(field('Quick filter', search), 'Shift+click a header to add a sort level. Try >5000 in Revenue.');

  const grid = createGrid<Order>(body, {
    columns,
    rows: makeOrders(2000),
    getRowId: (order) => order.id,
    defaultColumn: { sortable: true, filter: true },
    floatingFilters: true,
    multiSort: true,
    sort: [{ colId: 'revenue', dir: 'desc' }],
    theme: docsTheme(),
    ariaLabel: 'Orders with sorting and filtering',
  });

  const describe = () => {
    const sort =
      grid
        .getSort()
        .map((s) => `${s.colId} ${s.dir}`)
        .join(', ') || 'none';
    const filters = Object.keys(grid.getFilterModel()).join(', ') || 'none';
    const shown = grid.getDisplayRows().length;
    status.textContent = `${shown.toLocaleString()} of ${grid.getRows().length.toLocaleString()} orders. Sort: ${sort}. Filters: ${filters}.`;
  };
  const onInput = () => grid.setQuickFilter(search.value);
  search.addEventListener('input', onInput);
  const offs = [
    grid.on('modelUpdated', describe),
    grid.on('sortChanged', describe),
    grid.on('filterChanged', describe),
  ];
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  describe();

  return () => {
    search.removeEventListener('input', onInput);
    for (const off of offs) off();
    stopTheme();
    grid.destroy();
  };
}
```

## The sort model

The current sort is an array of `SortItem` objects. The first item is the primary sort key, the second breaks ties in the first, and so on.

**`SortItem`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface SortItem
```

| Property | Type | Description |
| --- | --- | --- |
| `colId` | `string` |  |
| `dir` | `SortDirection` |  |

Set an initial sort with the `sort` option:

```ts title="orders-grid.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

const grid = createGrid<Order>(document.querySelector('#orders')!, {
  columns,
  rows: orders,
  getRowId: (o) => o.id,
  sort: [
    { colId: 'region', dir: 'asc' },
    { colId: 'revenue', dir: 'desc' },
  ],
});
```

`colId` is the column ID, which is the `id` or `field` of the column. Items that refer to a missing column are ignored.

## Multi-column sorting

Hold <kbd>Shift</kbd>, <kbd>Ctrl</kbd> or <kbd>Cmd</kbd> while clicking a header to add that column to the existing sort instead of replacing it. Modifier-clicking a column that is already sorted moves it through descending and then out of the sort, leaving the other columns in place. The header shows ▲ or ▼, followed by the column's position in the sort when more than one column is sorted.

From the keyboard, focus a header and press <kbd>Enter</kbd> or <kbd>Space</kbd> to sort, or <kbd>Shift</kbd>+<kbd>Enter</kbd> to add the column to a multi-column sort. Every change is announced to screen readers, for example "Sorted by Revenue, descending".

Multi-column sorting is on by default. Set `multiSort: false` to make modifier clicks behave like plain clicks, so only one column is ever sorted:

```ts
createGrid(container, { columns, rows: orders, multiSort: false });
```

The header's column menu also offers **Sort ascending**, **Sort descending** and **Clear sort**. Open it with the menu button on the header, a right-click, or <kbd>Alt</kbd>+<kbd>Arrow Down</kbd> on a focused header.

## How values are compared

Without a comparator the grid compares by column type:

| Type | Comparison |
| --- | --- |
| `text` | `Intl.Collator` with numeric collation and base sensitivity: case-insensitive and accent-insensitive, and "Invoice 9" sorts before "Invoice 10". Uses the grid's `locale`. |
| `number` | Numeric. Numeric strings such as `"1,250"` are parsed first. |
| `date` | By timestamp. `Date` objects, epoch milliseconds and ISO strings can be mixed. |
| `boolean` | `false` before `true`. |

Two rules hold for every column:

- **Blank values sort last** in both directions. `null`, `undefined`, empty strings and `NaN` are blank.
- **Sorting is stable.** Rows that compare equal keep their previous relative order, so sorting by region and then by revenue behaves the way users expect.

The value compared is the column value, meaning the result of `valueGetter` when one is set, never the output of `format`.

## Custom comparators

A `comparator(a, b, rowA, rowB)` returns a negative number, zero or a positive number, like `Array.prototype.sort`. Write it for ascending order; the grid flips it for descending.

```ts
const statusRank: Record<Order['status'], number> = {
  Backordered: 0,
  Pending: 1,
  Shipped: 2,
  Cancelled: 3,
};

const columns: ColumnDef<Order>[] = [
  {
    field: 'status',
    comparator: (a, b) => statusRank[a as Order['status']] - statusRank[b as Order['status']],
  },
  {
    field: 'customer',
    comparator: (a, b, rowA, rowB) => rowB.lifetimeValue - rowA.lifetimeValue || String(a).localeCompare(String(b)),
  },
];
```

Blank values (`null`, `undefined` and empty strings) are sorted last before your comparator is consulted, so a comparator only ever compares two non-blank values. If a comparator throws, the grid reports the error with `console.error` and treats the pair as equal.

## Sorting from code

```ts
grid.setSort([{ colId: 'orderDate', dir: 'desc' }]);
grid.setSort([]);
const current = grid.getSort();
```

`update({ sort })` applies a sort the same way and also fires `sortChanged`; framework adapters use it when a bound `sort` prop changes.

**`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridApi<TRow = RowData> extends Widget<GridOptions<TRow>, GridEvents<TRow>>, GridFeatureApi<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `setSort` | `(sort: SortItem[]) => void` |  |
| `getSort` | `() => SortItem[]` |  |

## Reacting to sort changes

`sortChanged` fires whenever the sort changes, from the header or from code. Use it to persist the sort or to sort on the server.

```ts
grid.on('sortChanged', ({ sort }) => {
  localStorage.setItem('orders.sort', JSON.stringify(sort));
});

const saved = localStorage.getItem('orders.sort');
if (saved) grid.setSort(JSON.parse(saved));
```

### Server-side sorting

To let a backend sort, keep the rows in server order and turn the header clicks into requests. Use a comparator that returns `0` on every column so the grid's stable sort keeps the order you loaded:

```ts
const serverOrder = () => 0;

const grid = createGrid<Order>(container, {
  columns: columns.map((c) => ({ ...c, comparator: serverOrder })),
  rows: [],
  getRowId: (o) => o.id,
});

grid.on('sortChanged', async ({ sort }) => {
  const params = new URLSearchParams(sort.map((s) => ['sort', `${s.colId}:${s.dir}`]));
  const response = await fetch(`/api/orders?${params}`);
  grid.setRows(await response.json());
});
```

## Disabling sorting

```ts
const columns: ColumnDef<Order>[] = [
  { id: 'actions', header: '', sortable: false, cell: renderActions },
];

createGrid(container, { columns, rows, defaultColumn: { sortable: false } });
```

A column with `sortable: false` ignores header clicks, but you can still sort it from code with `setSort()`.

## Related

- [Filtering](https://docs.birchui.com/grid/filtering.md) runs before sorting in the pipeline.
- [Row grouping](https://docs.birchui.com/grid-pro/row-grouping.md) sorts within each group.
