Last active
September 3, 2021 13:34
-
-
Save 9point6/6988755 to your computer and use it in GitHub Desktop.
JavaScript & CoffeeScript function for sorting IP addresses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} ); | |
} |
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
Whelp, this is more useful than I expected. Thanks!