Version 6.3 Released!

Click to checkout the new features

Old Documentation
You are browsing documentation for an old version of Tabulator. Consider upgrading your project to Tabulator 6.3

Sorting Data

Overview

Tabulator allows you to sort the data in your table in any way you want either by clicking on column headers or by calling a number of sort functions on the table.

Programmatic Sort Parameters
Loading Example...
Source Code

HTML

<div>
      <select id="sort-field">
          <option value="name" selected>Name</option>
          <option value="progress">Progress</option>
          <option value="gender">Gender</option>
          <option value="rating">Rating</option>
          <option value="col">Favourite Colour</option>
          <option value="dob">Date Of Birth</option>
          <option value="car">Driver</option>
      </select>

      <select id="sort-direction">
          <option value="asc" selected>asc</option>
          <option value="desc">desc</option>
      </select>

    <button id="sort-trigger">Trigger Sort</button>
</div>

<div id="example-table"></div>

JavaScript

//Define variables for input elements
var fieldEl = document.getElementById("sort-field");
var dirEl = document.getElementById("sort-direction");

//Build Tabulator
var table = new Tabulator("#example-table", {
    height:"311px",
    layout:"fitColumns",
    columns:[
        {title:"Name", field:"name", width:200},
        {title:"Progress", field:"progress", hozAlign:"right", headerSortTristate:true},
        {title:"Gender", field:"gender", sorter:"string"},
        {title:"Rating", field:"rating",  hozAlign:"center", width:100},
        {title:"Favourite Color", field:"col", sorter:function(a,b){
            return String(a).toLowerCase().localeCompare(String(b).toLowerCase());
        }},
        {title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"},
        {title:"Driver", field:"car", hozAlign:"center", sorter:"boolean"},
    ],
});

//Trigger sort when "Trigger Sort" button is clicked
document.getElementById("sort-trigger").addEventListener("click", function(){
   table.setSort(fieldEl.options[fieldEl.selectedIndex].value, dirEl.options[dirEl.selectedIndex].value);
});

By default Tabulator will attempt to guess which sorter should be applied to a column based on the data contained in the first row. It can determine sorters for strings, numbers, alphanumeric sequences and booleans, anything else will be treated as a string.

To specify a sorter to be used on a column use the sorter property in the columns definition object

You can pass an optional additional property with sorter, sorterParams that should contain an object with additional information for configuring the sorter.

{title:"Birthday", field:"birthday", sorter:"date", sorterParams:{format:"dd/MM/yy"}}

Params Lookup Function

If you want to dynamically generate the sorterParams at the time the sort is called you can pass a function into the property that should return the params object.

//define lookup function
function paramLookup(column, dir){
    //column - the column component for the column being sorted
    //dir - the direction of the sort ("asc" or "desc")

    //do some processing and return the param object
    return {param1:"green"};
}

//column definition
{title:"Birthday", field:"birthday", sorter:"date", sorterParams:paramLookup}

Sort Order

When using multiple sorters, the order in the array is the order in which the sort functions will be applied to the data. In the example below the data will first be sorted by age, and then the result of that sort will be sorted by height. So the data displayed on screen will be sorted in order of height, with any equal height values being sorted by age. The same sort order applies when clicking on multiple column header sorts.

table.setSort([
    {column:"age", dir:"asc"}, //sort by this first
    {column:"height", dir:"desc"}, //then sort by this second
]);

Reverse Sort Order

If you would prefer the sorting to occur in the reverse order, to match the way that tables like excel sort, then you should set the sortOrderReverse to true in your table definition:

var table = new Tabulator("#example-table", {
    sortOrderReverse:true,
});

Built In Sorters

Tabulator comes with a number of preconfigured sorters including:

Note: For a guide to adding your own sorters to this list, have a look at the Extending Tabulator section.

String

The string sorter will sort columns as strings of characters

{title:"Example", field:"example", sorter:"string", sorterParams:{
    locale:true,
    alignEmptyValues:"top",
}}

The sorter has optional properties for the sorterParams object:

  • locale - the locale code for the string comparison function, (without this the sorter will use the locale of the browser). it can accept:
    • string - the locale code for the sort
    • boolean - set the value to true to use the current table locale
  • alignEmptyValues - force empty cells to top or bottom of table regardless of sort order, this property takes a string:
    • top - force empty cells to the top of the table
    • bottom - force empty cells to the bottom of the table

Numeric

The number sorter will sort column as numbers (integer or float, will also handle numbers using "," separators)

{title:"Example", field:"example", sorter:"number", sorterParams:{
    thousandSeparator:",",
    decimalSeparator:",",
    alignEmptyValues:"top",
}}

The sorter has optional properties for the sorterParams object:

  • thousandSeparator - if using a thousand separator character in your numbers (eg 1,024.00), then set it in this property to ensure the sorter works correctly
  • decimalSeparator - If you are using a decimal separator other than the standard "." (eg 1,45) then set it in this property to ensure the sorter works correctly
  • alignEmptyValues - force empty cells to top or bottom of table regardless of sort order, this property takes a string:
    • top - force empty cells to the top of the table
    • bottom - force empty cells to the bottom of the table

Alphanumeric

The alphanum sorter will sort column as alpha numeric code

{title:"Example", field:"example", sorter:"alphanum", sorterParams:{
    alignEmptyValues:"top",
}}

The sorter has optional properties for the sorterParams object:

  • alignEmptyValues - force empty cells to top or bottom of table regardless of sort order, this property takes a string:
    • top - force empty cells to the top of the table
    • bottom - force empty cells to the bottom of the table

Boolean

The boolean sorter will sort column as booleans

{title:"Example", field:"example", sorter:"boolean"}

Field Exists

The exists sorter will sort column ordering if value has a type of "undefined" or not

{title:"Example", field:"example", sorter:"exists"}

Date

Dependency Required
You will need to include the luxon.js library to use this sorter

The date sorter will sort columns as dates

{title:"Example", field:"example", sorter:"date", sorterParams:{
    format:"yyyy-MM-dd",
    alignEmptyValues:"top",
}}

The sorter has optional properties for the sorterParams object:

  • format - the format of the date (default: dd/MM/yyyy). This accepts any valid Luxon format string, or the value "iso" which accept any ISO formatted data. If the input value is a luxon DateTime object then you can ignore this option.
  • alignEmptyValues - force empty cells to top or bottom of table regardless of sort order, this property takes a string:
    • top - force empty cells to the top of the table
    • bottom - force empty cells to the bottom of the table

Time

Dependency Required
You will need to include the luxon.js library to use this sorter

The time sorter will sort columns as times

{title:"Example", field:"example", sorter:"time", sorterParams:{
    format:"HH:mm:ss",
    alignEmptyValues:"top",
}}

The sorter has optional properties for the sorterParams object:

  • format - the format of the date (default: HH:mm). This accepts any valid Luxon format string, or the value "iso" which accept any ISO formatted data. If the input value is a luxon DateTime object then you can ignore this option.
  • alignEmptyValues - force empty cells to top or bottom of table regardless of sort order, this property takes a string:
    • top - force empty cells to the top of the table
    • bottom - force empty cells to the bottom of the table

Date Time

Dependency Required
You will need to include the luxon.js library to use this sorter

The datetime sorter will sort columns as datetimes

{title:"Example", field:"example", sorter:"datetime", sorterParams:{
    format:"yyyy-MM-dd HH:mm:ss",
    alignEmptyValues:"top",
}}

The sorter has optional properties for the sorterParams object:

  • format - the format of the date (default: dd/MM/yy HH:mm:ss). This accepts any valid Luxon format string, or the value "iso" which accept any ISO formatted data. If the input value is a luxon DateTime object then you can ignore this option.
  • alignEmptyValues - force empty cells to top or bottom of table regardless of sort order, this property takes a string:
    • top - force empty cells to the top of the table
    • bottom - force empty cells to the bottom of the table

Array

The array sorter will sort arrays of data

{title:"Example", field:"example", sorter:"array", sorterParams:{
    type:"sum",
    alignEmptyValues:"top",
}}

The sorter has optional properties for the sorterParams object:

  • type - Arrays will be sorted by length by default, this property takes a string for the comparison type:
    • length - sort arrays by length
    • sum - sort arrays by sum of their value
    • max - sort arrays by maximum value
    • min - sort arrays by minimum value
    • avg - sort arrays by average value of all elements
  • alignEmptyValues - force empty cells to top or bottom of table regardless of sort order, this property takes a string:
    • top - force empty cells to the top of the table
    • bottom - force empty cells to the bottom of the table

Custom Sorters

for advanced sorting can define a custom sorter function in the sorter option:

{title:"Name", field:"name", sorter:function(a, b, aRow, bRow, column, dir, sorterParams){
    //a, b - the two values being compared
    //aRow, bRow - the row components for the values being compared (useful if you need to access additional fields in the row data for the sort)
    //column - the column component for the column being sorted
    //dir - the direction of the sort ("asc" or "desc")
    //sorterParams - sorterParams object from column definition array

    return a - b; //you must return the difference between the two values
},
}

The fifth parameter in this callback is a > for the column being sorted.

Header Sorting

By default all columns in a table are sortable by clicking on the column header, if you want to disable this behaviour, set the headerSort property to false.

This can be set per column in the column definition:

{title:"Name", field:"name", sorter:"string", headerSort:false} //disable header sorter

Multi Column Sorting

By default you can sort by multiple columns at the same time by holding the ctrl or shift key when you click on the column headers.

if you wish to disable this behaviour, so only once column can be sorted at a time, you can set the columnHeaderSortMulti option to false

var table = new Tabulator("#example-table", {
    columnHeaderSortMulti:false,
});

Header Sort Direction

By default Tabulator will sort a column in ascending order when a user first clicks on the column header.

The headerSortStartingDir property in the column definition can be used to set the starting sort direction when a user clicks on an unsorted column, it can either be set to asc or desc.

{title:"Name", field:"name", sorter:"string", headerSortStartingDir:"desc"} //start sorting column in descending order when user clicks on header of unsorted column

Tristate Header Sorting

By default once you click on a header to sort it the header will then toggle between sorting in ascending and descending order.

If you would prefer a third option of returning the column to its original unsorted order, the you can set the headerSortTristate option to true in the column definition. The sort will the toggle between the original order, ascending and descending order

This can be set per column in the column definition:

{title:"Name", field:"name", sorter:"string", headerSortTristate:true} //enable tristate header sort on column

Initial Sort

When the table is first created it can be defined with an initial set of sorters. These can be set using the initialSort option. This will take the same sorter array as the setSort function. (see Sorter Functions for more details)

var table = new Tabulator("#example-table", {
    initialSort:[
        {column:"age", dir:"asc"}, //sort by this first
        {column:"height", dir:"desc"}, //then sort by this second
    ]
});

Manage Sorting

Trigger Sorting Programmatically

You can trigger sorting using the setSort function

table.setSort("age", "asc");

The first argument of the function is the column to be sorted, this can be a field name or any of the standard Column Lookup Options. The second argument is a string representing the sort direction that can either be asc or desc

If you wish to sort by multiple columns then you can pass an array of sorting objects to this function, the data will then be sorted in the order of the objects.

table.setSort([
    {column:"age", dir:"asc"}, //sort by this first
    {column:"height", dir:"desc"}, //then sort by this second
]);

The column property of the object is the column to be sorted, this can be a field name or any of the standard Column Lookup Options. The dir property is a string representing the sort direction that can either be asc or desc

Get Current Sorters

If you need to retrieve the details of the currently sorted column at any point you can use the getSorters function.

table.getSorters();

This will return an array of sort objects with three properties, column the column component for the sorted column, field a string of the field name for the sorted column, and dir a string of either "asc" or "desc" indicating the direction of sort.

[
    {
        column:column,
        field:"age",
        dir:"asc"
    },
    {
        column:column,
        field:"height"
        dir:"desc"
    }
]

If the table is not currently sorted then the array will be empty.

Ajax Sorting

If you would prefer to sort your data server side rather than in Tabulator, you can use the sortMode option to send the sort data to the server instead of processing it client side

var table = new Tabulator("#example-table", {
    sortMode:"remote", //send sort data to the server instead of processing locally
});

An array of sorters objects will then be passed in the sorters parameter of the request, the name of this parameter can be set in the dataSendParams option, in the pagination module.

The array of sorter objects will take the same form as those returned from the getSorters function:

[
    {
        column:column,
        field:"age",
        dir:"asc"
    },
    {
        column:column,
        field:"height"
        dir:"desc"
    }
]

If the table is not currently sorted then the array will be empty.

Clear All Sorters

To remove all sorting from the table, call the clearSort function.

table.clearSort();

Header Sort Icon

By default Tabulator will use a caret arrow to indicate sort direction in a column's header. You can customise the icon used for the column header sort by passing in the HTML for the sorting element to the headerSortElement property.

The table will automatically vertically center the icon with the header text. It is worth noting that in order for the table to render correctly, the sorter icon used should not exceed the height of the title text

Two different approaches to customising the sort icon are shown below. Both examples use font awesome icon elements for the sort icon, but you could just as easily add any HTML you like.

Single Vertically Flipping Icon

In this example we will use one icon, and then use some CSS to change its colour and direction depending on the sort.

Using the headerSortElement we will define a single icon for the sorter element:

var table = new Tabulator("#table", {
    headerSortElement:"<i class='fas fa-arrow-up'></i>",
});

And then use CSS to define what it should look like in the different sort direction

/* Define the style when the column is not sorted */
.tabulator-col[aria-sort="none"] .tabulator-col-sorter i{
    color:#999;
}

/* Define the style when the column is sorted in ascending order */
.tabulator-col[aria-sort="asc"] .tabulator-col-sorter i{
    color:#f00;
}

/* Define the style when the column is sorted in descending order */
.tabulator-col[aria-sort="desc"] .tabulator-col-sorter i{
    color:#f00;
    transform: scaleY(-1); /* flip the icon vertically so the arrow points down */
}

Different Icons Depending on Sort Direction

In this example we will define different icons for the unsorterd, ascending and descending sorts, and then use some CSS to change its colour and direction depending on the sort.

Using the headerSortElement we will define a single icon for the sorter element:

var table = new Tabulator("#table", {
    headerSortElement:"<span><i class='fas fa-sort'></i><i class='fas fa-sort-up'></i><i class='fas fa-sort-down'></i></span>",
});

And then use CSS to define what it should look like in the different sort direction

/* Hide all icons by default */
.tabulator-col .tabulator-col-sorter i{
    display: none;
}

/* Display the fa-sort icon when the column is not sorted */
.tabulator-col[aria-sort="none"] .tabulator-col-sorter i.fa-sort{
    display: inline-block;
    color:#999;
}

/* Display the fa-sort-up icon when the column is sorted in ascending order */
.tabulator-col[aria-sort="asc"] .tabulator-col-sorter i.fa-sort-up{
    display: inline-block;
    color:#f00;
}

/* Display the fa-sort-down icon when the column is sorted in descending order */
.tabulator-col[aria-sort="desc"] .tabulator-col-sorter i.fa-sort-down{
    display: inline-block;
    color:#f00;
}

Events

A range of events are available for tracking the progress of sorting. See the Sorting Events section for more information.

Donate