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.

<

Configuring Sorting in Ag Grid

Sorting is a fundamental feature in Ag Grid that allows users to organize data in ascending or descending order based on column values. The grid provides built-in support for sorting, which can be easily enabled and customized according to specific requirements.

To enable sorting on columns, you can set the sortable property to true either globally or on a per-column basis:

  • Global sorting: Enable sorting on all columns by setting defaultColDef.sortable = true in the grid options.
  • Per-column sorting: Configure sorting individually by adding sortable: true in each column definition.
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.

Expert Perspectives on How To Sort In Ag Grid

Dr. Emily Chen (Senior Frontend Developer, TechGrid Solutions). Sorting in Ag Grid is fundamentally about leveraging the grid’s built-in API methods such as `setSortModel` to programmatically control sorting states. Understanding the distinction between single and multi-column sorting is crucial, as it allows developers to tailor the user experience effectively. Additionally, enabling server-side sorting requires careful integration with backend data services to maintain performance at scale.

Raj Patel (UI/UX Architect, DataViz Innovations). From a user interface perspective, implementing intuitive sorting in Ag Grid involves configuring sortable column definitions and providing clear visual cues like sort icons. It is important to consider accessibility standards, ensuring keyboard navigation and screen reader support when sorting is enabled. Custom comparator functions can also enhance sorting behavior for complex data types, improving overall usability.

Linda Martinez (Data Engineer, Enterprise Analytics Corp). Effective sorting in Ag Grid is essential for handling large datasets efficiently. Utilizing Ag Grid’s infinite row model alongside sorting capabilities allows for seamless data retrieval without overwhelming the client. Developers should also implement debounce mechanisms when sorting triggers data fetches to optimize network requests and maintain responsive interfaces.

Frequently Asked Questions (FAQs)

How do I enable sorting in AG Grid?
Sorting is enabled by setting the `sortable` property to `true` in the column definitions. For example, `{ field: ‘name’, sortable: true }` allows users to sort that column.

Can I implement multi-column sorting in AG Grid?
Yes, multi-column sorting is supported by enabling the `multiSortKey` property, which allows users to hold a key (such as Shift) while clicking multiple column headers to sort by multiple columns simultaneously.

How do I customize the sorting order in AG Grid?
You can customize sorting order by using the `sortOrder` property in the column definition or by implementing a custom comparator function via the `comparator` property.

Is it possible to disable sorting on specific columns?
Yes, sorting can be disabled on individual columns by setting the `sortable` property to “ in their column definitions.

How can I programmatically set the sort state in AG Grid?
Use the grid API method `setSortModel()` to programmatically define the sort model, specifying which columns to sort and their sort directions.

What types of data can AG Grid sort by default?
AG Grid supports default sorting for strings, numbers, and dates. For complex data types, a custom comparator function is required to define sorting behavior.
Sorting in AG Grid is a fundamental feature that enhances data presentation and user experience by allowing users to organize information efficiently. AG Grid supports multiple sorting modes, including single and multi-column sorting, which can be enabled and customized through grid options and column definitions. Developers can implement sorting either by using the built-in sorting capabilities or by creating custom sort comparators to handle complex data types or specific sorting logic.

Understanding how to configure sorting in AG Grid involves setting properties such as `sortable`, `sort`, and `multiSortKey` within column definitions and grid options. Additionally, AG Grid provides APIs and events that enable dynamic control over sorting behavior, allowing for programmatic sorting and responding to user interactions. This flexibility ensures that sorting can be tailored to meet diverse application requirements.

In summary, mastering sorting in AG Grid empowers developers to deliver intuitive and efficient data grids. By leveraging AG Grid’s comprehensive sorting features and customization options, one can significantly improve data accessibility and usability within web applications. Proper implementation of sorting not only enhances the overall functionality but also contributes to a more polished and professional user interface.

Author Profile

Avatar
Barbara Hernandez
Barbara Hernandez is the brain behind A Girl Among Geeks a coding blog born from stubborn bugs, midnight learning, and a refusal to quit. With zero formal training and a browser full of error messages, she taught herself everything from loops to Linux. Her mission? Make tech less intimidating, one real answer at a time.

Barbara writes for the self-taught, the stuck, and the silently frustrated offering code clarity without the condescension. What started as her personal survival guide is now a go-to space for learners who just want to understand what the docs forgot to mention.
Method Description Example Usage
setSortModel(sortModel) Sets the sorting model programmatically
gridApi.setSortModel([
  { colId: 'country', sort: 'asc' },
  { colId: 'year', sort: 'desc' }
]);
getSortModel() Retrieves the current sorting model const currentSort = gridApi.getSortModel();
refreshClientSideRowModel('sort') Refreshes the sort state without resetting the entire grid gridApi.refreshClientSideRowModel('sort');