Skip to content

Instantly share code, notes, and snippets.

@9point6
Last active September 3, 2021 13:34
Show Gist options
  • Save 9point6/6988755 to your computer and use it in GitHub Desktop.
Save 9point6/6988755 to your computer and use it in GitHub Desktop.
JavaScript & CoffeeScript function for sorting IP addresses
ipSort = ( ipAddressArray ) ->
ipAddressArray.sort ( a, b ) ->
a = a.split '.'
b = b.split '.'
for i of a
if ( a[i] = parseInt a[i] ) < ( b[i] = parseInt b[i] )
return -1
else if a[i] > b[i]
return 1
return 0
ipSort = function( ipAddressArray )
{
return ipAddressArray.sort( function( a, b )
{
a = a.split( '.' );
b = b.split( '.' );
for( var i = 0; i < a.length; i++ )
{
if( ( a[i] = parseInt( a[i] ) ) < ( b[i] = parseInt( b[i] ) ) )
return -1;
else if( a[i] > b[i] )
return 1;
}
return 0;
} );
}
@arfianadam
Copy link

Whelp, this is more useful than I expected. Thanks!

@bzalasky
Copy link

bzalasky commented Sep 11, 2018

Thanks for sharing this gist! If anyone needs to sort a collection of objects by an IP property, you can derive a comparator from the function above:

  ipComparator = (a, b) ->
    a = a?.split('.') or []
    b = b?.split('.') or []

    for i of a
      if (a[i] = parseInt a[i], 10) < (b[i] = parseInt b[i], 10)
        return -1
      else if a[i] > b[i]
        return 1

    return 0

...and use it like this:

networkCollection.sort((a, b) => ipComparator(a.ip, b.ip))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment