Sortable HTML table

A javascript for sorting HTML tables by column.

Sorting with a client-side script like this is faster than doing it on the server-side. You can also use HTML in the table cells, since only the text content is sorted. But if the HTML table is generated by a server-side script or database query in the first place, it might make more sense to do the sorting on that side as well.

Browser support

Should work in newer desktop browsers (2015), while mobile browsers seem less good at sorting letters beyond the ISO basic Latin alphabet (A-Z). But even buggy browsers should at least sort A-Z properly. I haven't tested non-Western alphabets.

Demo

Click a button in a column's top row to sort the table by that column. Click the button again to reverse the order.

Correct alphabetical sorting order

Example table 1 (in Swedish)
Number Swedish text Date
0.001 Älg 2006-09-23
0 Ödla 2006-10-22
-11 Åsna 1999-12-24
20 And 2006-10-24
Example table 2 (in German)
Temperature German text Time
+100° Zucker 20:00
Bär 19:30
-11° Bier 00:00
+25.5° Öl 23:59
Example table 3 (in English)
Price English text with HTML Weight
$100 Apples 1kg
$2,900.50 Oranges 20kg
$2,900
  • Cats
  • Dogs
  • Birds
0.1kg
$3.50 Turtles 1000kg

How it works

The script creates an array of the sorted column cells' text content (the following is ignored: leading and trailing whitespace, HTML, form field values, image ALT text and other HTML attribute values), then sorts the array. If the isNaN() method returns true for an array item, the array is sorted alphabetically, otherwise numerically. Finally the table rows are arranged in the same order as the sorted array.

Installation and configuration

To make a table sortable, add the custom attribute data-sortable-table. Multiple tables on the same page can be sorted.

Sorting by number

You can force a column with mixed content to be sorted numerically by adding the custom attribute data-sorting-type="number" to the column's TH element. Then the script ignores all characters except numbers, decimal periods and a beginning minus sign (-) when sorting. For example, "$2,500" should be sorted as "2500". This might be useful for numerical columns containing things like units, temperature or money symbols.

Sorting by text/string

Alphabetical sorting is done with the localeCompare() method , so that letters in different alphabets are (hopefully) sorted in correct order. For example, in German Ä and Ö should be sorted after A and O, respectively, while in Swedish Ä and Ö are distinct letters that appear last in the alphabet (after Z and Å).

The desired sorting language can be specified in an optional LANG attribute for each table, which the script then uses in localeCompare(). If no LANG attribute is specified the script defaults to "en" (English).

Special considerations

published: Nov 10, 2015
last modified: Jan 26, 2017