1

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?

1
  • How is it going? Have you solved the issue or still looking for some better answer? Commented Jul 23, 2019 at 15:39

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.