Sort a column with IP Addresses in a DataTable
Sort a column with IP Addresses in a DataTable
I dont know if this is the best way to publish my code, but i want to share it.
I had to search a way to sort a column with IP Addresses and this was my solution:
[code]
oTable = $('#example').dataTable({ /*Parameters*/ });
jQuery.fn.dataTableExt.aTypes.unshift(
function (sData) {
var bIp = false;
if (sData.match(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)$/)) {
bIp = true;
} else {
return null;
}
return 'ipaddress';
}
);
jQuery.fn.dataTableExt.oSort['ipaddress-asc'] = function (a, b) {
var x = a.split('.');
var y = b.split('.');
x = ("00" + x[0]).slice(-3) + ("00" + x[1]).slice(-3) + ("00" + x[2]).slice(-3) + ("00" + x[3]).slice(-3);
y = ("00" + y[0]).slice(-3) + ("00" + y[1]).slice(-3) + ("00" + y[2]).slice(-3) + ("00" + y[3]).slice(-3);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['ipaddress-desc'] = function (a, b) {
var x = a.split('.');
var y = b.split('.');
x = ("00" + x[0]).slice(-3) + ("00" + x[1]).slice(-3) + ("00" + x[2]).slice(-3) + ("00" + x[3]).slice(-3);
y = ("00" + y[0]).slice(-3) + ("00" + y[1]).slice(-3) + ("00" + y[2]).slice(-3) + ("00" + y[3]).slice(-3);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
[/code]
I had to search a way to sort a column with IP Addresses and this was my solution:
[code]
oTable = $('#example').dataTable({ /*Parameters*/ });
jQuery.fn.dataTableExt.aTypes.unshift(
function (sData) {
var bIp = false;
if (sData.match(/^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)$/)) {
bIp = true;
} else {
return null;
}
return 'ipaddress';
}
);
jQuery.fn.dataTableExt.oSort['ipaddress-asc'] = function (a, b) {
var x = a.split('.');
var y = b.split('.');
x = ("00" + x[0]).slice(-3) + ("00" + x[1]).slice(-3) + ("00" + x[2]).slice(-3) + ("00" + x[3]).slice(-3);
y = ("00" + y[0]).slice(-3) + ("00" + y[1]).slice(-3) + ("00" + y[2]).slice(-3) + ("00" + y[3]).slice(-3);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['ipaddress-desc'] = function (a, b) {
var x = a.split('.');
var y = b.split('.');
x = ("00" + x[0]).slice(-3) + ("00" + x[1]).slice(-3) + ("00" + x[2]).slice(-3) + ("00" + x[3]).slice(-3);
y = ("00" + y[0]).slice(-3) + ("00" + y[1]).slice(-3) + ("00" + y[2]).slice(-3) + ("00" + y[3]).slice(-3);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
[/code]
This discussion has been closed.
Replies
There is actually (sorry to say) an IP address sorter already: https://github.com/DataTables/Plugins/blob/master/sorting/ip-address.js .
Allan