Sort IP Address AngularJS

1.5k views Asked by At

I have a table header IP Address, that use AngularJS to sort it. Unfortunately, it doesn't seem to sort IP address.

<th class="text-left">
    <a href="" ng-click="sortType = 'device.ip_address'; sortReverse = !sortReverse">
        IP Address
    </a>
</th>

enter image description here

I want to use something like this

sortFn: function (a, b) {
    if (a == b) return 0;
    if ( +a.replace(/\./g, '') < +b.replace(/\./g, '')) return - 1;
    return 1;
}

How do I use this function above as my sort function in AngularJS?

3

There are 3 answers

0
Slava Utesinov On BEST ANSWER

You should normalize IPs (for example, from 192.168.1.1 to 192.168.001.001) to properly compare them:

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.ips = [
    "192.168.1.1",
    "192.168.2.3",
    "192.168.1.00",
    "192.168.1.3"
  ]
  $scope.sortIps = function(ip) {    
    return ip.split('.').map(function(x) {
      return x.padStart(3, "0");
    }).join('');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  <a ng-init='sortReverse=false' href="" ng-click="sortReverse = !sortReverse">
      IP Address
  </a>  
  <ul>
    <li ng-repeat='ip in ips | orderBy : sortIps : sortReverse'>{{ip}}</li>
  </ul>
</div>

5
NTP On

If you are using ng-repeat to display rows of your table you don't have to create your custom function just convert the Ip address to number

$scope.sortIp = function(ip){
    return parseInt(ip.split('.').join(""));
};

and let orderBy filter of angularjs do the job for you.

<button ng-click="order = !order">Order</button>
<div ng-repeat="item in items | orderBy:sortIp:order ">
    {{item}}
</div>

also orderBy takes a second parameter (true / false) for asc / desc ordering

Demo

0
nomadus On

I use the following function to sort IP addresses

const convertToNumber = (address) => {
    if (address === null || address === undefined) return null;
    if (address.indexOf(".") < 0) return address.padEnd(12, "0");

    return parseInt((address.split(".")
        .map(item => item.padEnd(3, "0"))
        .join("").padEnd(12,"0")));
};

For above IP addresses, you shall have ips = [ "192.168.1.1", "192.168.2.3", "192.168.1.00", "192.168.1.3" ].map(item=>console.log(convertToNumber(item)));

192168100100 192168200300 192168100000 192168100300,

The same approach can be applied to sort document sections (1.1, 1.1.1, 2.1.2 etc)