---
title: "Row Sorting"
framework: javascript
version: "36.1.0"
---

# Row Sorting

This page describes how to sort row data in the grid and how you can customise that sorting to match your requirements.

## Sorting

Sorting is enabled by default for all columns. You can sort a column by clicking on the column header. To enable / disable sorting per column use the `sortable` column definition attribute.

```js
const gridOptions = {
    columnDefs: [
        { field: 'name' },
        { field: 'age' },
        // disable sorting by address
        { field: 'address', sortable: false },
    ],

    // other grid options ...
}
```

To disable sorting for all columns, set sorting in the [default column definition](https://www.ag-grid.com/javascript-data-grid/column-definitions/).

```js
const gridOptions = {
    // disable sorting on all columns
    defaultColDef: {
        sortable: false
    },
    columnDefs: [
        // Override default to enable sorting by name
        { field: 'name', sortable: true },
        { field: 'age' },
        { field: 'address' },
    ],

    // other grid options ...
}
```

## Custom Sorting

Custom sorting is provided at a column level by configuring a comparator on the column definition.

```js
const gridOptions = {
    columnDefs: [
        {
            field: 'age',
            // simple number comparator
            comparator: (valueA, valueB, nodeA, nodeB, isDescending) => valueA - valueB
        },
        {
            field: 'name',
            // simple string comparator
            comparator: (valueA, valueB, nodeA, nodeB, isDescending) => {
                if (valueA == valueB) return 0;
                return (valueA > valueB) ? 1 : -1;
            }
        }
    ],

    // other grid options ...
}
```

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `comparator` | `SortComparatorFn \| Partial<Record<SortType, SortComparatorFn>>` |  |  | Override the default sorting order by providing a custom sort comparator, or a map of comparators for different `SortType`s. - `valueA`, `valueB` are the values to compare. - `nodeA`, `nodeB` are the corresponding RowNodes. Useful if additional details are required by the sort. - `isDescending` - `true` if sort direction is `desc`. Not to be used for inverting the return value as the grid already applies `asc` or `desc` ordering. Returns: - `0` valueA is the same as valueB - `> 0` Sort valueA after valueB - `< 0` Sort valueA before valueB |

Example below shows the following:

- The **Athlete** column is sorted descending on load.
- When the **Year** column is not sorted, it shows a custom icon (up/down arrow).
- The **Date** column has strings as the row data, but has a custom comparator so that when you sort this column it sorts as dates, not as strings.

#### Custom Sorting

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

const columnDefs: ColDef[] = [
  { field: "athlete", sort: "desc" },
  { field: "age", width: 90 },
  { field: "country" },
  { field: "year", width: 120, unSortIcon: true },
  { field: "date", comparator: dateComparator },
  { field: "sport" },
];

function dateComparator(date1: string, date2: string) {
  const date1Number = monthToComparableNumber(date1);
  const date2Number = monthToComparableNumber(date2);

  if (date1Number === null && date2Number === null) {
    return 0;
  }
  if (date1Number === null) {
    return -1;
  }
  if (date2Number === null) {
    return 1;
  }

  return date1Number - date2Number;
}

// eg 29/08/2004 gets converted to 20040829
function monthToComparableNumber(date: string) {
  if (date === undefined || date === null || date.length !== 10) {
    return null;
  }
  const yearNumber = Number.parseInt(date.substring(6, 10));
  const monthNumber = Number.parseInt(date.substring(3, 5));
  const dayNumber = Number.parseInt(date.substring(0, 2));

  return yearNumber * 10000 + monthNumber * 100 + dayNumber;
}

let gridApi: GridApi<IOlympicData>;

const gridOptions: GridOptions<IOlympicData> = {
  columnDefs: columnDefs,
  defaultColDef: {
    width: 170,
  },
};

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data: IOlympicData[]) =>
    gridApi!.setGridOption("rowData", data.slice(0, 10)),
  );
```

[Live example: Custom Sorting](https://www.ag-grid.com/examples/row-sorting/custom-sorting/typescript)

> **Note**
>
> If you are using a custom column header component see [Custom Components](https://www.ag-grid.com/javascript-data-grid/column-headers-components/#custom-component) for how to implement sorting.

## Multi Column Sorting

It is possible to sort by multiple columns. The default action for multiple column sorting is for the user to hold down `⇧ Shift` while clicking the column header. To change the default action to use the `^ Ctrl` key instead set the property `multiSortKey='ctrl'`.

The example below demonstrates the following:

- The grid sorts by **Country** then **Athlete** by default.
- The property `multiSortKey='ctrl'` is set so multiple column sorting is achieved by holding down `^ Ctrl` and selecting multiple columns.

#### Multi Column Sort

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  ColumnApiModule,
  ColumnState,
  GridApi,
  GridOptions,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ColumnApiModule, ClientSideRowModelModule]);

const columnDefs: ColDef[] = [
  { field: "athlete" },
  { field: "age", width: 100 },
  { field: "country" },
  { field: "year", width: 100 },
  { field: "date" },
  { field: "sport" },
  { field: "gold" },
  { field: "silver" },
  { field: "bronze" },
  { field: "total" },
];

let gridApi: GridApi<IOlympicData>;

const gridOptions: GridOptions<IOlympicData> = {
  columnDefs: columnDefs,
  defaultColDef: {
    width: 170,
  },
  multiSortKey: "ctrl",
  onGridReady: (params) => {
    const defaultSortModel: ColumnState[] = [
      { colId: "country", sort: "asc", sortIndex: 0 },
      { colId: "athlete", sort: "asc", sortIndex: 1 },
    ];

    params.api.applyColumnState({ state: defaultSortModel });
  },
};

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
```

[Live example: Multi Column Sort](https://www.ag-grid.com/examples/row-sorting/multi-column/typescript)

> **Note**
>
> You can suppress the multi sorting behaviour by enabling the `suppressMultiSort` option, or force the behaviour without key press by enabling the `alwaysMultiSort` option.

## Sorting Animation

By default rows will animate after sorting. If you wish to suppress this animation set the grid property `animateRows=false`.

## Sorting Order

By default, the sorting order is as follows:

**ascending -> descending -> none**.

In other words, when you click a column that is not sorted, it will sort ascending. The next click will make it sort descending. Another click will remove the sort.

It is possible to override this behaviour by providing your own `sortingOrder` on the `colDef`.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sortingOrder` | `(SortDirection \| SortDef)[]` |  |  | An array defining the order in which sorting occurs (if sorting is enabled). Defaults: - `['asc', 'desc', null]` if no sort type is specified, - `[{ type: 'absolute', direction: 'asc', }, { type: 'absolute', direction: 'desc' }, null]` if 'sort' or 'initialSort' have type 'absolute' |

The example below shows different combinations of sorting orders as follows:

- **Column Athlete:** ascending -> descending
- **Column Age:** descending -> ascending
- **Column Country:** descending -> no sort
- **Column Year:** ascending only
- **Default Columns:** descending -> ascending -> no sort

#### Sorting Order and Animation

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

const columnDefs: ColDef[] = [
  { field: "athlete", sortingOrder: ["asc", "desc"] },
  { field: "age", width: 90, sortingOrder: ["desc", "asc"] },
  { field: "country", sortingOrder: ["desc", null] },
  { field: "year", width: 90, sortingOrder: ["asc"] },
  { field: "date" },
  { field: "sport" },
  { field: "gold" },
  { field: "silver" },
  { field: "bronze" },
  { field: "total" },
];

let gridApi: GridApi<IOlympicData>;

const gridOptions: GridOptions<IOlympicData> = {
  defaultColDef: {
    width: 170,
    sortingOrder: ["desc", "asc", null],
  },
  columnDefs: columnDefs,
};

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
```

[Live example: Sorting Order and Animation](https://www.ag-grid.com/examples/row-sorting/sorting-order-and-animation/typescript)

## Absolute Sorting

Absolute Sorting enables sorting numeric values based on their magnitude, ignoring their sign. This can be used to rank values by their size ignoring if a value is positive or negative.

In the following example, the column `rankingChange` uses absolute sorting:

```js
const gridOptions = {
    columnDefs: [
        // ... other columns
        {
            field: 'rankingChange',
            sort: { direction: 'asc', type: 'absolute' },
            sortingOrder: [
                { direction: 'asc', type: 'absolute' },
                { direction: 'desc', type: 'absolute' },
                null,
            ],
        },
    ],

    // other grid options ...
}
```

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `sort` | `SortDirection \| SortDef` |  |  | Set the default sort. |
| `sortingOrder` | `(SortDirection \| SortDef)[]` |  |  | An array defining the order in which sorting occurs (if sorting is enabled). Defaults: - `['asc', 'desc', null]` if no sort type is specified, - `[{ type: 'absolute', direction: 'asc', }, { type: 'absolute', direction: 'desc' }, null]` if 'sort' or 'initialSort' have type 'absolute' |

#### Absolute Value Sorting

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { any } from "./interfaces";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

const columnDefs: ColDef[] = [
  { field: "athlete", minWidth: 150 },
  { field: "year", maxWidth: 90 },
  {
    field: "rankingChange",
    sort: { direction: "asc", type: "absolute" },
    sortingOrder: [
      { direction: "asc", type: "absolute" },
      { direction: "desc", type: "absolute" },
      null,
    ],
  },
];

let gridApi: GridApi<IOlympicData>;

const gridOptions: GridOptions<any> = {
  defaultColDef: {
    flex: 1,
    minWidth: 100,
  },

  columnDefs,
};

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/small-olympic-winners.json")
  .then((response) => response.json())
  .then((data: IOlympicData[]) =>
    gridApi!.setGridOption(
      "rowData",
      data.map((item) => {
        return {
          ...item,
          rankingChange: Math.round(window.agRandom() * 10) - 5,
        };
      }),
    ),
  );
```

[Live example: Absolute Value Sorting](https://www.ag-grid.com/examples/row-sorting/absolute-sorting/typescript)

## Sorting API

> **Note**
>
> The sort state can be saved and restored as part of [Grid State](https://www.ag-grid.com/javascript-data-grid/grid-state/).

What sorting is applied is controlled via [Column State](https://www.ag-grid.com/javascript-data-grid/column-state/). The below examples uses the Column State API to control column sorting.

#### Sorting API

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  ColumnApiModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  NumberFilterModule,
  TextFilterModule,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  TextFilterModule,
  NumberFilterModule,
  ClientSideRowModelModule,
  ColumnApiModule,
]);

const columnDefs: ColDef[] = [
  { field: "athlete" },
  { field: "age", width: 90 },
  { field: "country" },
  { field: "sport" },
  { field: "year", width: 90 },
  { field: "date" },
  { field: "gold" },
  { field: "silver" },
  { field: "bronze" },
  { field: "total" },
];

let gridApi: GridApi<IOlympicData>;

const gridOptions: GridOptions<IOlympicData> = {
  columnDefs: columnDefs,
};

function sortByAthleteAsc() {
  gridApi!.applyColumnState({
    state: [{ colId: "athlete", sort: "asc" }],
    defaultState: { sort: null },
  });
}

function sortByAthleteDesc() {
  gridApi!.applyColumnState({
    state: [{ colId: "athlete", sort: "desc" }],
    defaultState: { sort: null },
  });
}

function sortByCountryThenSport() {
  gridApi!.applyColumnState({
    state: [
      { colId: "country", sort: "asc", sortIndex: 0 },
      { colId: "sport", sort: "asc", sortIndex: 1 },
    ],
    defaultState: { sort: null },
  });
}

function sortBySportThenCountry() {
  gridApi!.applyColumnState({
    state: [
      { colId: "country", sort: "asc", sortIndex: 1 },
      { colId: "sport", sort: "asc", sortIndex: 0 },
    ],
    defaultState: { sort: null },
  });
}

function clearSort() {
  gridApi!.applyColumnState({
    defaultState: { sort: null },
  });
}

let savedSort: any;

function saveSort() {
  const colState = gridApi!.getColumnState();
  const sortState = colState
    .filter(function (s) {
      return s.sort != null;
    })
    .map(function (s) {
      return { colId: s.colId, sort: s.sort, sortIndex: s.sortIndex };
    });
  savedSort = sortState;
  console.log("saved sort", sortState);
}

function restoreFromSave() {
  gridApi!.applyColumnState({
    state: savedSort,
    defaultState: { sort: null },
  });
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).sortByAthleteAsc = sortByAthleteAsc;
  (<any>window).sortByAthleteDesc = sortByAthleteDesc;
  (<any>window).sortByCountryThenSport = sortByCountryThenSport;
  (<any>window).sortBySportThenCountry = sortBySportThenCountry;
  (<any>window).clearSort = clearSort;
  (<any>window).saveSort = saveSort;
  (<any>window).restoreFromSave = restoreFromSave;
}
```

[Live example: Sorting API](https://www.ag-grid.com/examples/row-sorting/sorting-api/typescript)

## Locale-specific Sort

By default, sorting is not locale-specific and strings are compared using their Unicode code point order. There is no language awareness and no locale rules are applied. If you need to make your sort locale-specific you can configure this by setting the grid option `accentedSort = true`.

> **Note**
>
> Locale-specific sort is slower than default sort which may be noticeable when sorting a large number of rows.

Toggle the buttons in the following example to see the difference between default sorting and locale-aware sorting. Note that with locale-aware sorting, the order is `a à b c` instead of the default Unicode order of `a b c à`.

#### Locale Aware Sort

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

const columnDefs: ColDef[] = [
  { headerName: "Locale-specific Sort", field: "letter", sort: "asc" },
];

function applyLocale() {
  gridApi!.updateGridOptions({
    accentedSort: true,
    columnDefs: [
      { field: "letter", sort: "asc", headerName: "Locale-specific Sort" },
    ],
  });
}

function applyDefault() {
  gridApi!.updateGridOptions({
    accentedSort: false,
    columnDefs: [{ field: "letter", sort: "asc", headerName: "Default Sort" }],
  });
}

let gridApi: GridApi;

const gridOptions: GridOptions = {
  columnDefs: columnDefs,
  accentedSort: true,
  rowData: [..."bàac"].map((x) => ({ letter: x })),
};

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).applyLocale = applyLocale;
  (<any>window).applyDefault = applyDefault;
}
```

[Live example: Locale Aware Sort](https://www.ag-grid.com/examples/row-sorting/locale-aware-sort/typescript)

## Post-Sort

It is also possible to perform some post-sorting if you require additional control over the sorted rows.

This is provided via the `postSortRows` grid callback function as shown below:

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `postSortRows` | `PostSortRows` |  |  | Callback to perform additional sorting after the grid has sorted the rows. When configured, `deltaSort` is ignored. |

```js
const gridOptions = {
    postSortRows: params => {
        let rowNodes = params.nodes;
        // here we put Ireland rows on top while preserving the sort order
        let nextInsertPos = 0;
        for (let i = 0; i < rowNodes.length; i++) {
            const country = rowNodes[i].data.country;
            if (country === 'Ireland') {
                rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
                nextInsertPos++;
            }
        }
    },

    // other grid options ...
}
```

The following example uses this configuration to perform a post-sort on the rows. The custom function puts rows with Ireland at the top always.

#### Post Sort

```ts
import {
  ClientSideRowModelModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  PostSortRowsParams,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

let gridApi: GridApi<IOlympicData>;

const gridOptions: GridOptions<IOlympicData> = {
  columnDefs: [
    { field: "athlete" },
    { field: "age", width: 100 },
    { field: "country", sort: "asc" },
    { field: "year" },
    { field: "date" },
    { field: "sport" },
    { field: "gold" },
    { field: "silver" },
    { field: "bronze" },
    { field: "total" },
  ],
  defaultColDef: {
    width: 170,
  },
  postSortRows: (params: PostSortRowsParams<IOlympicData>) => {
    const rowNodes = params.nodes;
    // here we put Ireland rows on top while preserving the sort order
    let nextInsertPos = 0;
    for (let i = 0; i < rowNodes.length; i++) {
      const country = rowNodes[i].data ? rowNodes[i].data!.country : undefined;
      if (country === "Ireland") {
        rowNodes.splice(nextInsertPos, 0, rowNodes.splice(i, 1)[0]);
        nextInsertPos++;
      }
    }
  },
};

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data) => {
    gridApi!.setGridOption("rowData", data);
  });
```

[Live example: Post Sort](https://www.ag-grid.com/examples/row-sorting/post-sort/typescript)
