JQuery DataTable Birthday Sort

I’m working on a project that uses DataTables a JQuery plug-in that turns ordinary table into dynamic tables. One of the columns includes a list of birthdays. We didn’t want the standard date sorting. We wanted the birthdays to sort primarily by month. Below you will see the custom sort algorithm I came up with to sort our birthdays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function sortdatatable(a,b){
	//a is blank return 1 to sort after b
	if(a == '') return 1;
	//b is blank return 0 no change
	if(b == '') return 0;
 
	//Split dates on / 
	//format expected is mm/dd/yyyy
	//array 0 is month
	//array 1 is day
	//array 1 is year
	var x = a.split('/'), y = b.split('/');
 
	//Parse month strings to int for comparison
	var xInt = parseInt(x[0]), yInt = parseInt(y[0]);
 
	//If months are the same check days.
	if(xInt == yInt){
		//Parse day strings to int for comparison
		var x1Int =parseInt(x[1]), y1Int = parseInt(y[1]);
 
		//if days are the same check years
		if(x1Int == y1Int){
			//Parse day strings to int for comparison
			var x2Int = parseInt(x[2]), y2Int = parseInt(y[2]);
 
			//if years are the same return 0.
			//if xInt is smaller than yInt return 1 to sort after y else return -1 
			return x2Int == y2Int ? 0 : x2Int < y2Int ? 1 : -1;
		} else {
			//if xInt is smaller than yInt return 1 to sort after y else return -1 
			return x1Int < y1Int ? 1 : -1;
		}
	} else {
		//if xInt is smaller than yInt return 1 to sort after y else return -1 
		return xInt < yInt ? 1 : -1;
	}
}
 
jQuery.fn.dataTableExt.oSort['birthday-asc'] = function(a, b) {
	return -(sortdatatable(a,b));
};
 
jQuery.fn.dataTableExt.oSort['birthday-desc'] = function(a, b) {
	return sortdatatable(a,b);
};

The meat of the sorting is the sortdatatable function. The algorithm sorts according to descending order. We compare the months first. If the months are the same we compare days and if the days are the same we compare years. If months, days, and years are all the same we return 0 to leave those two items in the same order.

The ascending and descending algorithms are the inverse of each other. So to save space in the JavaScript file we use the same function and return the -(sortdatatable(a,b)) for the ascending sort.

I began programming in C++ when I was in college. Odd for a business major, but hey I am a Dork. After college I got a job as System Administrator. As a System Administrator I was in charge of web administration. My journey as a PHP web developer had begun. Since that time I have gained an in depth knowledge of CSS, Javascript, XML and MySQL. With changes and advances to technology I have also began learning AJAX. I started Blue Fire Development to do freelance work in my spare time.

Posted in JavaScript, JQuery, Programming Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*