I am using DataTables, a Table plug-in for jQuery, as a tool on my web design. But I encounter a problem since I would like to sort a column by partial value.
For example, there is a column named "Speaker", with values "Prof. Lin", "Dr. Yu", "Prof. Chen", and so on. When sorting the column, the order will be:
1."Dr. Yu"
2."Prof. Chen"
3."Prof. Lin".
I would like to sort by their first name rather than the first letter, which means ordering as:
1."Prof. Chen"
2."Prof. Lin"
3."Dr. Yu".
Another example is a column "Average(5% bias)" with values "78.0 (-2.5~2.5)", "90.5 (-1.5~1.5)", "130.0 (-3.0~3.0)", and so on. When sorting the column, the order will be:
1."130.0 (-3.0~3.0)"
2."78.0 (-2.5~2.5)"
3."90.5 (-1.5~1.5)".
I would like to sort by their average value rather than the first letter (DataTable thinks the column values are string rather than float), which means ordering as:
1."78.0 (-2.5~2.5)"
2."90.5 (-1.5~1.5)"
3."130.0 (-3.0~3.0)".
In my database, there are two columns to store the data, like "title" and "forst_name", "average" and "bias". So it is easy to separate as two parts in a <td></td>
tag.
Is it possible to sort a column by partial value using DataTables?
Asked
Active
Viewed 1,483 times
1

Vicki Lin
- 63
- 6
-
Does the [custom sorting plugins](https://www.datatables.net/plug-ins/sorting/) for datatables help? – Slartibartfast Sep 17 '15 at 01:58
1 Answers
3
I have done a sample code for the Title
sort. You may do the rest for the Average
column.
Markup
<table id="report">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dr. Yu</td>
</tr>
<tr>
<td>Prof. Chen</td>
</tr>
<tr>
<td>Prof. Lin</td>
</tr>
</tbody>
</table>
JavaScript/jQuery
$(document).ready(function () {
function getValue(titleValue) {
return titleValue.replace(/^Prof\.\s+|^Dr\.\s+/g, '');
}
jQuery.fn.dataTableExt.oSort['title-asc'] = function (a, b) {
var x = getValue(a);
var y = getValue(b);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['title-desc'] = function (a, b) {
var x = getValue(a);
var y = getValue(b);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
$('#report').dataTable({"aoColumns": [
{ "sType": "title" }
]});
});
Thanks to this post

Community
- 1
- 1

James Jithin
- 10,183
- 5
- 36
- 51
-
Thank you very much!! I write another function for average data column: function getValue(averageValue) { return parseFloat(averageValue.substring(0, averageValue.indexOf('('))); } – Vicki Lin Sep 17 '15 at 07:46