Steven Sann
Steven Sann

Reputation: 578

Custom sorting DataTables column by date part of the value

I use jQuery DataTables in my code.
One of my columns has values, like:

AB 05-05-2019
CD 01-05-2019
EF 09-05-2019

When I click this column's header, I want it to get sorted only by using date, not by the prefix ('AB', 'CD', 'EF'). The result should be like:

CD 01-05-2019
AB 05-05-2019
EF 09-05-2019 

What I've tried is, inserting a hidden column only with the date and when I sort column with the prefix, I sort my hidden column using JavaScript.
But, is there any proper way by using default configuration of jQuery DataTables?

Upvotes: 1

Views: 298

Answers (1)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

Assuming, your values are dates in the format 'DD-MM-YYYY' prefixed by two characters and a space, you may built your own little sorting plug-in, with custom sorting function like that:

(first, second) => {
    const firstDate = new Date(first.substr(3).split('-').reverse().join('-'));
    const secondDate = new Date(second.substr(3).split('-').reverse().join('-'));
    return firstDate - secondDate;
};

So, your complete example might look something like this:

//source data
const srcData = [{
		id: 1,
		value: 'AB 05-05-2019'
	}, {
		id: 2,
		value: 'CD 01-05-2019'
	}, {
		id: 3,
		value: 'EF 09-05-2019'
	}
];

//datatable initialization
const dataTable = $('#mytable').DataTable({
		dom: 't',
		data: srcData,
		columns: ['id', 'value'].map(header => ({
				title: header,
				data: header
			})),
		columnDefs: [{
				type: 'prefixedDate',
				targets: 1
			}
		]
	});
//extract Date part of the string
const extractDate = str => new Date(str.substr(3).split('-').reverse().join('-'));

//custom sorting
Object.assign($.fn.DataTable.ext.oSort, {
  'prefixedDate-asc': (a, b) => extractDate(a) - extractDate(b),
  'prefixedDate-desc': (a, b) => extractDate(b) - extractDate(a),
});
<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>

Upvotes: 1

Related Questions