Sort a column with IP Addresses in a DataTable

Sort a column with IP Addresses in a DataTable

ZetAZetA Posts: 2Questions: 0Answers: 0
edited February 2014 in General
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]

Replies

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Nice one - thanks for sharing this with us. There is a Plug-ins repo for DataTables so devs such as yourself can share plug-ins: https://github.com/DataTables/Plugins .

    There is actually (sorry to say) an IP address sorter already: https://github.com/DataTables/Plugins/blob/master/sorting/ip-address.js .

    Allan
This discussion has been closed.