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 through
onDataRequestwhendataMode: 'backend'
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 } ], 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, { dataMode: 'backend', onDataRequest: async ({ startRow, endRow, query }) => { const response = await fetch('/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ startRow, endRow, query }) });
return response.json(); }});Sorting only runs in backend mode when dataMode is explicitly set to 'backend'. In auto mode, onDataRequest is still used for row loading, but sorting stays frontend.
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.