"
DataGridXL 3 Out Now! See what's new→

Column Sort Function

Data inside the grid can be sorted by column. This is an undoable action, just like in MS Excel & Google Spreadsheets.

The performSort undoable action is available in the context menu. Right-click on a column header to see two sort options: one to sort ascending ("A to Z"), one to sort descending ("Z to A").

Sort by code

To sort the data grid by code, use the performSort method. Note that the sort action will always be added on top of the undo-stack, no matter if it is initiated by the user or by code.

javascript
const grid = new DataGridXL("grid", ...);

// sort sheet by column at column coordinate 2
// in ascending direction ("A to Z")
grid.performSort(2, "asc");

Advanced

The performSort method calls the undoable sort action. The sort action calls sortUsingInstructions, a Sheet method.

This method sorts column values by a simple default sort function.

javascript
function defaultSortFunction(a,b){

  // we probably need a `sortableValue` property...
  // convert `true`/`false` to something that is comparable
  
  return String(a.value).localeCompare(String(b.value));

}

If your column represents a specific type of values, such as dates or numbers, this default sort function will fall short.

In that case, add a sortFunction property to your column settings:

javascript
{
  "title": "My Column",
  "sortFunction": customSortFunction
}

For instance, to sort numbers, make your sortFunction look like this:

javascript
// sort numbers
// before: [5, 3, 8, 1, 2]
// after: [1, 2, 3, 5, 8]
function customSortFunction(a,b){
  return a - b;
}

In case you want to sort date strings ("YYYY-MM-DD"), your sortFunction can look like this:

javascript
// sort date strings
// before: ["2023-12-01", "2022-06-15", "2023-05-20", "2021-08-30"]
// after: ["2021-08-30", "2022-06-15", "2023-05-20", "2023-12-01"]
function customSortFunction(a,b){
  return new Date(a) - new Date(b);
}

You only have to supply a sort function that sorts ascending, DataGridXL internal code will reverse your sort function in case of descending sort direction.

Generated: 25.01.28 (V3.25.01.22)