Sorting the columns

You can make the Table sortable with a callback that triggers whenever a column is clicked. We ship the Table with a built-in sort mechanism, but you'll still need to call it. The sort method takes a column index and a direction.

  • ts.ui.get('#example6', table => {
    	table.cols(
    		['Animal', {label: 'Price', type: 'ts-number'}]
    	).rows([
    		['Donkey', 700],
    		['Baboon', 1500],
    		['Coyote', 250],
    		['Albatross', 50]
    	]).sortable(function(index, ascending) {
    		table.sort(index, ascending);
    	});
    	table.sort(0, true);
    });
    

The index is the column index and the ascending argument alternates whenever the same col is clicked twice. If you manage your own sorting routine, you can control the appearance of the column using selected and ascending.

  • ts.ui.get('#example12', table => {
    	table.cols([
    		{
    			label: 'Example',
    			selected: true,
    			ascending: false
    		}
    	]);
    	setInterval(function() {
    		var col = table.cols()[0];
    		if((col.selected = !col.selected)) {
    			col.ascending = !col.ascending;
    		}
    	}, 1000);
    });
    

Importantly note that the cell values must all be declared as numbers in order to sort numerically. You can declare a hidden value while showing a human readable text using verbose syntax:

table.rows([
	[
		{value: 1, text: 'One'},
		{value: 2, text: 'Two'},
		{value: 3, text: 'Three'}
	]
]);

Custom sort

Standard sorting only deals with numbers and strings. If you need some kind of more advanced sorting, for example if the value contains arrays or objects, you can implement custom sort per column via the sort method.

  • ts.ui.get('#example7', table => {
    	table.cols([
    		{
    			label: 'Fruit',
    			sort: function(val1, val2, ascending) { // sort random!
    				return Math.random() > 0.5 ? 1 : -1;
    			}
    		}
    	])
    	.rows([['Banana'], ['Apple'], ['Grape'], ['Pear']])
    	.sortable(function(index, ascending) {
    		table.sort(index, ascending);
    	});
    });