How Do You Sort Data in AG Grid?
Sorting data efficiently is a fundamental feature in any data grid, and when it comes to powerful, flexible grid solutions, AG Grid stands out as a top choice for developers and businesses alike. Whether you’re managing vast datasets or building interactive dashboards, understanding how to sort in AG Grid can dramatically enhance the user experience by making data more accessible and easier to analyze.
Sorting in AG Grid isn’t just about arranging rows alphabetically or numerically; it’s about leveraging a robust set of options that cater to diverse needs—from simple single-column sorts to complex multi-column sorting with custom logic. This capability empowers users to quickly find patterns, prioritize information, and make informed decisions without sifting through endless data manually.
As you dive deeper into this topic, you’ll discover how AG Grid’s sorting features integrate seamlessly with its other functionalities, offering a smooth, intuitive interface for both developers and end-users. Whether you’re new to AG Grid or looking to refine your skills, mastering sorting will unlock new levels of efficiency and clarity in your data presentations.
Configuring Sorting in Ag Grid
Ag Grid offers comprehensive sorting capabilities that can be configured both declaratively through column definitions and programmatically via the grid API. Sorting behavior is controlled primarily by the `sortable` property on each column definition. By default, setting `sortable: true` enables sorting for that column, allowing users to click the column header to sort the data in ascending or descending order.
Beyond the basic toggle, developers can customize the sorting logic by providing a `comparator` function in the column definition. This function allows for advanced sorting scenarios, such as sorting complex data types, case-insensitive strings, or custom object properties.
Key configuration options for sorting in Ag Grid include:
- sortable: Enables or disables sorting on a column (`true` or “).
- sort: Specifies the initial sort direction (`’asc’`, `’desc’`, or `null` for none).
- sortIndex: Determines the order of multi-column sorting.
- comparator: A custom function to define sorting logic.
- suppressSorting: Disables sorting interaction while keeping the column header interactive.
Enabling and Using Multi-Column Sorting
Ag Grid supports multi-column sorting, allowing users to sort by multiple columns sequentially. This is typically activated by holding down the Shift key while clicking column headers. To enable multi-column sorting, set the grid property `multiSortKey` to specify the key used to trigger multi-sort (e.g., `’ctrl’` or `’shift’`).
Programmatically, multi-column sorting can be controlled using the `sortModel` property or API methods such as `setSortModel()`. The `sortModel` is an array of objects, each defining a column and its sort direction. For example:
“`js
[
{ colId: ‘country’, sort: ‘asc’ },
{ colId: ‘year’, sort: ‘desc’ }
]
“`
This model sorts first by country ascending, then by year descending.
To enable multi-column sorting:
- Set `gridOptions.multiSortKey = ‘ctrl’` or `’shift’`.
- Use the Shift or Ctrl key to add to the sort sequence when clicking column headers.
- Manage sorting programmatically via the API for precise control.
Custom Sorting with Comparator Functions
When default sorting is insufficient, Ag Grid allows developers to implement custom sorting logic through comparator functions. A comparator function receives two parameters representing the values from two rows and must return:
- A negative number if the first value should come before the second,
- Zero if they are equivalent,
- A positive number if the first value should come after the second.
This approach is essential when sorting complex data types, such as dates stored as strings, nested objects, or case-insensitive strings.
Example of a case-insensitive string comparator:
“`js
function caseInsensitiveComparator(valueA, valueB) {
if (valueA == null) return -1;
if (valueB == null) return 1;
return valueA.toString().toLowerCase().localeCompare(valueB.toString().toLowerCase());
}
“`
Assign this comparator to the column definition:
“`js
{
field: ‘name’,
sortable: true,
comparator: caseInsensitiveComparator
}
“`
Sorting API Methods
Ag Grid exposes several API methods to control sorting dynamically, which is useful for integrating with external controls or implementing custom sorting behavior.
API Method | Description |
---|---|
`setSortModel()` | Sets the entire sort state programmatically. |
`getSortModel()` | Retrieves the current sort model from the grid. |
`sortColumn()` | Sorts a single column with a specified direction. |
`clearSort()` | Removes all sorting from the grid. |
Example: Setting a sort model programmatically
“`js
gridOptions.api.setSortModel([
{ colId: ‘athlete’, sort: ‘asc’ },
{ colId: ‘age’, sort: ‘desc’ }
]);
“`
This will apply a multi-column sort where the data is first sorted by athlete name ascending, then by age descending.
Sorting Behavior and User Interaction
When sorting is enabled, users can interact with column headers to change the sort order. The default sorting cycle progresses through these states:
- No sort
- Ascending sort
- Descending sort
- No sort (cycle repeats)
This behavior can be altered by using the `suppressRemoveSort` property to prevent cycling back to no sort, or by implementing custom header components for more complex interactions.
Additionally, the `unSortIcon` property controls whether an icon is displayed when no sort is applied, improving visual feedback for users.
Sorting with Server-Side Data
In scenarios involving large datasets or server-side operations, sorting is often delegated to the backend. Ag Grid supports server-side sorting by sending the current sort model to the server on data requests. The server then processes the sort and returns sorted data.
To enable server-side sorting:
- Set `serverSideSortingAlwaysResets` if needed to control sort reset behavior.
- Use the `getServerSideDatasource()` method to integrate server communication.
- Listen for sorting changes via events like `sortChanged` to trigger data reloads.
This approach ensures efficient handling of sorting for large datasets without overloading the client.
Property | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sortable | boolean | Enables sorting on the column. | ||||||||||||||||||||
sort | string | Initial sort direction (‘asc’ or ‘desc’). | ||||||||||||||||||||
comparator | function |
Option | Description | Example |
---|---|---|
defaultColDef.sortable | Enables sorting on all columns by default | defaultColDef: { sortable: true } |
colDef.sortable | Enables sorting on a specific column | { field: 'name', sortable: true } |
Once sorting is enabled, users can click on the column headers to toggle between ascending, descending, and no sort states. The default sort order cycles through these states automatically.
Implementing Multi-Column Sorting
Ag Grid supports multi-column sorting, allowing users to sort data by more than one column simultaneously. This is particularly useful when sorting by primary and secondary criteria.
To enable multi-column sorting, use the multiSortKey
property in grid options:
multiSortKey: 'ctrl'
– Users hold the Ctrl key (Cmd on Mac) while clicking column headers to add that column to the sort.multiSortKey: 'shift'
– Users hold the Shift key instead.multiSortKey: null
– Disables multi-column sorting.
Example configuration:
gridOptions = {
defaultColDef: { sortable: true },
multiSortKey: 'ctrl'
};
When multi-column sorting is active, the sort order is displayed using small numbers in the column headers indicating the priority of sorting.
Sorting with Custom Comparator Functions
By default, Ag Grid uses built-in comparators to sort values based on their type (string, number, date). For complex sorting logic or custom data types, you can provide a comparator function within the column definition.
The comparator function signature is:
function comparator(valueA, valueB, nodeA, nodeB, isInverted) {
// return negative if valueA < valueB
// return positive if valueA > valueB
// return 0 if equal
}
- Parameters:
valueA
,valueB
: The values to compare.nodeA
,nodeB
: Row nodes for the values.isInverted
: Boolean indicating if the sort is descending.
Example of a custom comparator that sorts dates stored as strings in format ‘DD-MM-YYYY’:
function dateComparator(date1, date2) {
const [day1, month1, year1] = date1.split('-').map(Number);
const [day2, month2, year2] = date2.split('-').map(Number);
const dt1 = new Date(year1, month1 - 1, day1);
const dt2 = new Date(year2, month2 - 1, day2);
return dt1 - dt2;
}
const columnDefs = [
{
field: 'date',
sortable: true,
comparator: dateComparator
}
];
Programmatic Control of Sorting State
Ag Grid allows programmatic manipulation of sorting, enabling developers to set, clear, or modify sorting through its API.
Method | Description | Example Usage |
---|---|---|
setSortModel(sortModel) |
Sets the sorting model programmatically |
|
getSortModel() |
Retrieves the current sorting model | const currentSort = gridApi.getSortModel(); |
refreshClientSideRowModel('sort') |
Refreshes the sort state without resetting the entire grid | gridApi.refreshClientSideRowModel('sort'); |