I have a situation where I need to render a table using Datatables. However, I need to be able to sort it horizontally (left to right) instead of vertically (top to bottom). Is there any way I can do this?
Illustration: Columns are A,B,C,D,E. Rows are R1,R2,R3,R4...R30. I don't want to sort A to E, but I do want to sort any one of R1 to R30 so that A-E gets rearranged. For instance, for R1, the ascending order of values might be A,E,D,B,C and for R2's values, it might be D,E,B,A,C. I should be able to click on a row index (first column in that row) and see my columns reordered. (Default is rows being reordered)
Update: I found this example for horizontal sorting Sorting Table Columns with jQuery Table Sorter, but how do I get this to work with datatables?
you can use: columns().order()
var table = $('#example').DataTable();
table
.columns( '.status' )
.order( 'desc' )
.draw();
More info: https://datatables.net/reference/api/columns().order()
EDIT
You can achieve this by using the dataTables.colReorder.min.js plugin, you might want to disable the drag and drop initialy...in anycase:
var table = $('#example').DataTable({
colReorder: true
});
table.on('click', 'td:first-of-type', function() {
var values = [];
var row = $(this).parent();
row.children('td').each(function(i){
values.push($(this).text());
});
var colOrder = values.sortIndices;
table.colReorder.order(colOrder);
});
//get index after sort
//credit to this post:
//http://stackoverflow.com/questions/3730510/javascript-sort-array-and-return-an-array-of-indicies-that-indicates-the-positi
function sortWithIndeces(toSort) {
for (var i = 0; i < toSort.length; i++) {
toSort[i] = [toSort[i], i];
}
toSort.sort(function(a, b) {
return a[0] - b[0]
});
toSort.sortIndices = [];
for (var j = 0; j < toSort.length; j++) {
toSort.sortIndices.push(toSort[j][1]);
toSort[j] = toSort[j][0];
}
return toSort;
}
Full working example here: https://jsfiddle.net/qjp8Lnam/6/