Sorting

Sort grid data with single or multi-column sorting, custom comparators, and backend support.

ZenGrid provides powerful sorting capabilities with support for both single and multi-column sorting, custom comparators, and backend integration.

Sorting Modes

ZenGrid supports two sorting modes:

  • frontend: Data is sorted in the browser using the configured comparators
  • backend: Sorting is delegated to the server via the onSortRequest callback

Basic Sorting

basic-sort.js
// Sort a column in ascending order
grid.sort('name', 'asc');
// Sort a column in descending order
grid.sort('age', 'desc');
// Toggle sort direction (asc → desc → null → asc)
grid.toggleSort('email');
// Clear all sorting
grid.clearSort();

Configuration

sort-config.js
const grid = new ZenGrid(container, {
columns: [
{ id: 'name', field: 'name', sortable: true },
{ id: 'age', field: 'age', sortable: true },
{ id: 'email', field: 'email', sortable: false }
],
sortMode: 'frontend', // 'frontend' | 'backend'
sortIcons: {
asc: '▲',
desc: '▼'
}
});
Info

By default, all columns are sortable. Set sortable: false on individual columns to disable sorting.

Multi-Column Sorting

ZenGrid automatically supports multi-column sorting:

multi-sort.js
// Sort by name first, then by age
grid.sort('name', 'asc');
grid.sort('age', 'asc'); // Adds to existing sort
// Get current sort state
const sortState = grid.getSortState();
// Returns: [
// { column: 'name', direction: 'asc', sortIndex: 0 },
// { column: 'age', direction: 'asc', sortIndex: 1 }
// ]
💡 Tip

Hold Shift while clicking column headers to add additional sort levels in the UI.

Sort State Management

Getting Sort State

get-sort-state.js
// Get all active sorts
const allSorts = grid.getSortState();
// Get sort state for a specific column
const columnSort = grid.getColumnSort('name');
// Returns: { column: 'name', direction: 'asc', sortIndex: 0 } | null

Setting Sort State

set-sort-state.js
// Apply a sort configuration
grid.setSortState([
{ column: 'name', direction: 'asc' },
{ column: 'age', direction: 'desc' }
]);
// Clear all sorts
grid.setSortState([]);

Sort State Interface

types.ts
interface SortState {
column: string; // Column ID
direction: 'asc' | 'desc' | null;
sortIndex?: number; // Position in multi-sort sequence
}

Backend Sorting

For large datasets, delegate sorting to the server:

backend-sort.js
const grid = new ZenGrid(container, {
sortMode: 'backend',
onSortRequest: async (sortState) => {
// sortState: SortState[]
const response = await fetch('/api/data', {
method: 'POST',
body: JSON.stringify({ sort: sortState })
});
const newData = await response.json();
grid.setData(newData);
}
});
Warning

In backend mode, you are responsible for fetching and setting the sorted data. The grid will not perform any client-side sorting.

Custom Sort Icons

Customize the sort indicator icons:

custom-icons.js
const grid = new ZenGrid(container, {
sortIcons: {
asc: '↑',
desc: '↓'
}
});

Sorting Architecture

ZenGrid uses different sorter implementations based on your needs:

  • SingleColumnSorter: Optimized for single-column sorting
  • MultiColumnSorter: Handles multi-column sort sequences
  • SortStateManager: Tracks and manages sort state changes

Events

Listen to sort changes with these events:

sort-events.js
grid.on('sort:beforeSort', (event) => {
console.log('About to sort:', event.sortState);
// Return false to cancel the sort
});
grid.on('sort:change', (event) => {
console.log('Sort changed:', event.sortState);
});
grid.on('sort:afterSort', (event) => {
console.log('Sort completed:', event.sortState);
});

Example: Custom Comparator

custom-comparator.js
const grid = new ZenGrid(container, {
columns: [
{
id: 'status',
field: 'status',
sortable: true,
comparator: (a, b, direction) => {
const priority = { high: 3, medium: 2, low: 1 };
const diff = priority[a] - priority[b];
return direction === 'asc' ? diff : -diff;
}
}
]
});
💡 Tip

Custom comparators receive the cell values and the current sort direction, allowing you to implement domain-specific sorting logic.