Sorting on IP address

Sorting on IP address

nowordsnowords Posts: 8Questions: 0Answers: 0
edited April 2012 in DataTables 1.9
Maybe odd, but it was handy to use this sorting on IP address in CIDR notation.
for example, we have a subnet/size like: 111.16.32.0/24

[code]
function dot2num(dot) {
var d = dot.split('.');
return ((((((+d[0]) * 256) + (+d[1])) * 256) + (+d[2])) * 256) + (+d[3]);
}

function clean_subnet_size (ip) {
ip = ip.replace(/\/[0-9][0-9]/, "");
return ip;
}

$.fn.dataTableExt.oSort['string-ip-asc'] = function (x, y) {
x = clean_subnet_size(x);
x = dot2num(x);
y = clean_subnet_size(y);
y = dot2num(y);

return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};

$.fn.dataTableExt.oSort['string-ip-desc'] = function (x, y) {
x = clean_subnet_size(x);
x = dot2num(x);
y = clean_subnet_size(y);
y = dot2num(y);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
[/code]
And do not forget specify column type for sorting in table initiation.
Second column is the column for ip sorting.
[code]
"aoColumns": [
null,
{ "sType": 'string-ip' },
null
],

[/code]

Replies

  • allanallan Posts: 63,692Questions: 1Answers: 10,500 Site admin
    Fantastic! Thanks for sharing this with us :-)

    Allan
This discussion has been closed.