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
onSortRequestcallback
Basic Sorting
// Sort a column in ascending ordergrid.sort('name', 'asc');
// Sort a column in descending ordergrid.sort('age', 'desc');
// Toggle sort direction (asc → desc → null → asc)grid.toggleSort('email');
// Clear all sortinggrid.clearSort();Configuration
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: '▼' }});By default, all columns are sortable. Set sortable: false on individual columns to disable sorting.
Multi-Column Sorting
ZenGrid automatically supports multi-column sorting:
// Sort by name first, then by agegrid.sort('name', 'asc');grid.sort('age', 'asc'); // Adds to existing sort
// Get current sort stateconst sortState = grid.getSortState();// Returns: [// { column: 'name', direction: 'asc', sortIndex: 0 },// { column: 'age', direction: 'asc', sortIndex: 1 }// ]Hold Shift while clicking column headers to add additional sort levels in the UI.
Sort State Management
Getting Sort State
// Get all active sortsconst allSorts = grid.getSortState();
// Get sort state for a specific columnconst columnSort = grid.getColumnSort('name');// Returns: { column: 'name', direction: 'asc', sortIndex: 0 } | nullSetting Sort State
// Apply a sort configurationgrid.setSortState([ { column: 'name', direction: 'asc' }, { column: 'age', direction: 'desc' }]);
// Clear all sortsgrid.setSortState([]);Sort State Interface
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:
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); }});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:
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:
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
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; } } ]});Custom comparators receive the cell values and the current sort direction, allowing you to implement domain-specific sorting logic.