DataTables logo DataTables

Sorting plug-ins

DataTables provides two APIs for sorting information in a table. They can be used together or independently, and are fully described on the sorting development page.

Sorting functions (type based column sorting)

The main DataTables package includes sorting functions for string, date and numeric data, but you may very well wish to order data in some other manner (for example currency, formatting numbers, multi-part data etc). The sorting function pairs below provide a wealth of different sorting methods.

It is also worth noting that sorting function go hand-in-hand with type detection functions, and many of the function pairs below has a corresponding type detection function to make installation very easy.

Commas for decimal place
Show details
It is not uncommon for non-English speaking countries to use a comma for a decimal place. This sorting plug-in shows how that can be taken account of in sorting by adding the type 'numeric-comma' to DataTables. A type detection plug-in for this sorting method is provided below.
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.oSort['numeric-comma-asc']  = function(a,b) {
	var x = (a == "-") ? 0 : a.replace( /,/, "." );
	var y = (b == "-") ? 0 : b.replace( /,/, "." );
	x = parseFloat( x );
	y = parseFloat( y );
	return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['numeric-comma-desc'] = function(a,b) {
	var x = (a == "-") ? 0 : a.replace( /,/, "." );
	var y = (b == "-") ? 0 : b.replace( /,/, "." );
	x = parseFloat( x );
	y = parseFloat( y );
	return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};
Currency
Show details
This plug-in will provide numeric sorting for currency columns (either detected automatically with the currency type detection plug-in or set manually) while taking account of the currency symbol ($ or £ by default).
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a,b) {
	/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
	var x = a == "-" ? 0 : a.replace( /,/g, "" );
	var y = b == "-" ? 0 : b.replace( /,/g, "" );
	
	/* Remove the currency sign */
	x = x.substring( 1 );
	y = y.substring( 1 );
	
	/* Parse and return */
	x = parseFloat( x );
	y = parseFloat( y );
	return x - y;
};

jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a,b) {
	/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
	var x = a == "-" ? 0 : a.replace( /,/g, "" );
	var y = b == "-" ? 0 : b.replace( /,/g, "" );
	
	/* Remove the currency sign */
	x = x.substring( 1 );
	y = y.substring( 1 );
	
	/* Parse and return */
	x = parseFloat( x );
	y = parseFloat( y );
	return y - x;
};
Date (dd/mm/YYY hh:ii:ss)
Show details
This plug-in will provide date sorting for the "dd/mm/YYY hh:ii:ss" formatting, which is common in France and other European countries. It can also be quickly adapted for other formatting as required. Furthermore, this date sorting plug-in allows for empty values in the column.
Author: Ronan Guilloux
Code:
function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

jQuery.fn.dataTableExt.oSort['date-euro-asc'] = function(a, b) {
	if (trim(a) != '') {
		var frDatea = trim(a).split(' ');
		var frTimea = frDatea[1].split(':');
		var frDatea2 = frDatea[0].split('/');
		var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
	} else {
		var x = 10000000000000; // = l'an 1000 ...
	}

	if (trim(b) != '') {
		var frDateb = trim(b).split(' ');
		var frTimeb = frDateb[1].split(':');
		frDateb = frDateb[0].split('/');
		var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;		                
	} else {
		var y = 10000000000000;		                
	}
	var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
	return z;
};

jQuery.fn.dataTableExt.oSort['date-euro-desc'] = function(a, b) {
	if (trim(a) != '') {
		var frDatea = trim(a).split(' ');
		var frTimea = frDatea[1].split(':');
		var frDatea2 = frDatea[0].split('/');
		var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;		                
	} else {
		var x = 10000000000000;		                
	}

	if (trim(b) != '') {
		var frDateb = trim(b).split(' ');
		var frTimeb = frDateb[1].split(':');
		frDateb = frDateb[0].split('/');
		var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;		                
	} else {
		var y = 10000000000000;		                
	}		            
	var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));		            
	return z;
}; 
Date (dd/mm/YY)
Show details
DataTables internal date sorting replies on Date.parse() which is part of the Javascript language, but you may wish to sort on dates which is doesn't recognise. The following is a plug-in for sorting dates in the format dd/mm/yy. Note a type detection plug-in is provided to automatically select this type of sorting when needed (see below).
Author: Andy McMaster
Code:
jQuery.fn.dataTableExt.oSort['uk_date-asc']  = function(a,b) {
	var ukDatea = a.split('/');
	var ukDateb = b.split('/');
	
	var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
	var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;
	
	return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['uk_date-desc'] = function(a,b) {
	var ukDatea = a.split('/');
	var ukDateb = b.split('/');
	
	var x = (ukDatea[2] + ukDatea[1] + ukDatea[0]) * 1;
	var y = (ukDateb[2] + ukDateb[1] + ukDateb[0]) * 1;
	
	return ((x < y) ? 1 : ((x > y) ?  -1 : 0));
};
Formatted numbers
Show details
Removes any non-numeric (or a dot) characters, such that you can format numbers (for example 1,000,000) for easy reading. This plug-in allows those formatted numbers to be sorted numerically.
Author: Peter Gallagher
Code:
jQuery.fn.dataTableExt.oSort['formatted-num-asc'] = function(x,y){
 x = x.replace(/[^\d\-\.\/]/g,'');
 y = y.replace(/[^\d\-\.\/]/g,'');
 if(x.indexOf('/')>=0)x = eval(x);
 if(y.indexOf('/')>=0)y = eval(y);
 return x/1 - y/1;
}
jQuery.fn.dataTableExt.oSort['formatted-num-desc'] = function(x,y){
 x = x.replace(/[^\d\-\.\/]/g,'');
 y = y.replace(/[^\d\-\.\/]/g,'');
 if(x.indexOf('/')>=0)x = eval(x);
 if(y.indexOf('/')>=0)y = eval(y);
 return y/1 - x/1;
}
Hidden title numeric sorting
Show details
An alternative to the formatted number sorting function above (particularly useful when considering localisation which uses dots/periods for 10^3 separation rather than decimal places). Another method of overcoming it difficulties of sorting formatted numbers is to have the data to be sorted upon separate from the visual data. This sorting function pair will use the 'title' attribute of en empty span element (or anything else) to sort numerically (for example <span title="1000000"><span>1'000'000).
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.oSort['title-numeric-asc']  = function(a,b) {
	var x = a.match(/title="*([0-9]+)/)[1];
	var y = b.match(/title="*([0-9]+)/)[1];
	x = parseFloat( x );
	y = parseFloat( y );
	return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['title-numeric-desc'] = function(a,b) {
	var x = a.match(/title="*([0-9]+)/)[1];
	var y = b.match(/title="*([0-9]+)/)[1];
	x = parseFloat( x );
	y = parseFloat( y );
	return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};
Hidden title string sorting
Show details
Just like the "hidden title numeric sorting" plug-in above, this sorting plug-in will take the information to be sorted on from the title attribute of a span element. The only difference is that it is string based sorting rather than numeric.
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.oSort['title-string-asc']  = function(a,b) {
	var x = a.match(/title="(.*?)"/)[1].toLowerCase();
	var y = b.match(/title="(.*?)"/)[1].toLowerCase();
	return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['title-string-desc'] = function(a,b) {
	var x = a.match(/title="(.*?)"/)[1].toLowerCase();
	var y = b.match(/title="(.*?)"/)[1].toLowerCase();
	return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};
IP addresses
Show details
Sorts a column containing IP addresses in typical dot notation. This can be most useful when using DataTables for a networking application, and reporting information containing IP address. Also has a matching type detection plug-in for automatic type detection.
Author: Brad Wasson
Code:
jQuery.fn.dataTableExt.oSort['ip-address-asc']  = function(a,b) {
	var m = a.split("."), x = "";
	var n = b.split("."), y = "";
	for(var i = 0; i < m.length; i++) {
		var item = m[i];
		if(item.length == 1) {
			x += "00" + item;
		} else if(item.length == 2) {
			x += "0" + item;
		} else {
			x += item;
		}
	}
	for(var i = 0; i < n.length; i++) {
		var item = n[i];
		if(item.length == 1) {
			y += "00" + item;
		} else if(item.length == 2) {
			y += "0" + item;
		} else {
			y += item;
		}
	}
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};

jQuery.fn.dataTableExt.oSort['ip-address-desc']  = function(a,b) {
	var m = a.split("."), x = "";
	var n = b.split("."), y = "";
	for(var i = 0; i < m.length; i++) {
		var item = m[i];
		if(item.length == 1) {
			x += "00" + item;
		} else if (item.length == 2) {
			x += "0" + item;
		} else {
			x += item;
		}
	}
	for(var i = 0; i < n.length; i++) {
		var item = n[i];
		if(item.length == 1) {
			y += "00" + item;
		} else if (item.length == 2) {
			y += "0" + item;
		} else {
			y += item;
		}
	}
	return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
Natural sorting
Show details
Data can often be a complicated mix of numbers and letters (file names are a common example) and sorting them in a natural manner is quite a difficult problem. Fortunately a deal of work has already been done in this area by other authors - the following plug-in uses the naturalSort() function by Jim Palmer (download it here) to provide natural sorting in DataTables.
Author: Jim Palmer
Code:
jQuery.fn.dataTableExt.oSort['natural-asc']  = function(a,b) {
	return naturalSort(a,b);
};

jQuery.fn.dataTableExt.oSort['natural-desc'] = function(a,b) {
	return naturalSort(a,b) * -1;
};
Numbers with HTML
Show details
This sorting plug-in allows for HTML tags with numeric data. With the 'html' type it will strip the HTML and then sorts by strings, with this type it strips the HTML and then sorts by numbers. Note also that this sorting plug-in has an equivalent type detection plug-in which can make integration easier.
Author: Allan Jardine
Code:
jQuery.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
	var x = a.replace( /<.*?>/g, "" );
	var y = b.replace( /<.*?>/g, "" );
	x = parseFloat( x );
	y = parseFloat( y );
	return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
	var x = a.replace( /<.*?>/g, "" );
	var y = b.replace( /<.*?>/g, "" );
	x = parseFloat( x );
	y = parseFloat( y );
	return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};
Week day sorting
Show details
Sort data containing the week day (in English) chronologically.
Author: Pål Oliver Kristiansen
Code:
var weekdays = new Array();
weekdays['monday'] = 1;
weekdays['tuesday'] = 2;
weekdays['wednesday'] = 3;
weekdays['thursday'] = 4;
weekdays['friday'] = 5;
weekdays['saturday'] = 6;
weekdays['sunday'] = 7;

jQuery.fn.dataTableExt.oSort['weekdays-sort-asc']  = function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    return ((weekdays[a] < weekdays[b]) ? -1 : ((weekdays[a] > weekdays[b]) ?  1 : 0));
};

jQuery.fn.dataTableExt.oSort['weekdays-sort-desc'] = function(a,b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    return ((weekdays[a] < weekdays[b]) ? 1 : ((weekdays[a] > weekdays[b]) ?  -1 : 0));
};

Custom data source sorting

The custom data source functions are used to update the cached data in DataTables, so sorting can occur on columns with user input information.

Input element data source
Show details
Read information from a column of input (type text) elements and return an array to use as a basis for sorting.
Author: Allan Jardine
Code:
$.fn.dataTableExt.afnSortData['dom-text'] = function  ( oSettings, iColumn )
{
	var aData = [];
	$( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
		aData.push( this.value );
	} );
	return aData;
}
Select menu data source
Show details
Read information from a column of select (drop down) menus and return an array to use as a basis for sorting.
Author: Allan Jardine
Code:
$.fn.dataTableExt.afnSortData['dom-select'] = function  ( oSettings, iColumn )
{
	var aData = [];
	$( 'td:eq('+iColumn+') select', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
		aData.push( $(this).val() );
	} );
	return aData;
}
Checkbox data source
Show details
Read information from a column of checkboxes (input elements with type checkbox) and return an array to use as a basis for sorting.
Author: Allan Jardine
Code:
$.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, iColumn )
{
	var aData = [];
	$( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
		aData.push( this.checked==true ? "1" : "0" );
	} );
	return aData;
}

Note that all contributed code is copyright to the original author, unless otherwise stated.