Natural order (sort) array of hostname
npm install hostname-natural-order





Natural order (natural sort) for array of hostnames.
This library is using compare function from natural-orderby.
- hostname-natural-order
- When do you need this package?
- Installation
- Usage
- Using Array.prototype.sort
- Natural order/sort array of object
- Command-Line Interface (CLI)
- CLI Installation
- CLI Usage
- Limitation
- Changelog
- License
If you just use standard Array.prototype.sort, it would sort incorrectly and return:
- www1.example.org
- www1.test.org
- www100.example.org
- www2.example.org
- www2.test.org
- www200.example.org
That order is not what you expect? Here come a package to order that correctly.
npm i hostname-natural-order
`Usage
$3
`javascript
const { compare: compareHostname } = require('hostname-natural-order');const domains = [
'test.org',
'org',
'a.test.net',
'net',
'c.test.net',
'3.b.test.net',
'100.b.test.net',
'example.org',
'2.b.test.net',
'test.net',
'c.test.net',
'1.b.test.net',
];
domains.sort(compareHostname);
console.log(JSON.stringify(domains, null, 2));
`Will print:
`
[
"net",
"test.net",
"a.test.net",
"1.b.test.net",
"2.b.test.net",
"3.b.test.net",
"100.b.test.net",
"c.test.net",
"c.test.net",
"org",
"example.org",
"test.org"
]
`$3
Since v1.1.0, this package export "orderBy" method so you can order array of object easily.`javascript
const { orderBy } = require('hostname-natural-order');const hostnameList = [
{ name: '2.b.test.net' },
{ name: 'test.net' },
{ name: '1.b.test.net' },
{ name: '8.8.4.4' },
{ name: '100.100.100.100' },
{ name: 'example.org' },
{ name: '100.b.test.net' },
{ name: '8.8.8.8' },
{ name: 'test.org' },
{ name: 'a.test.net' },
{ name: 'c.test.net' },
{ name: '1.1.1.1' },
{ name: 'net' },
{ name: 'org' },
{ name: 'c.test.net' },
];
const hostnameListSorted = orderBy(
hostnameList,
// example to order by "name" property
(item) => item.name,
);
`Command-Line Interface (CLI)
This module provide CLI tool so you can use it from CLI shell directly without programming any code.$3
`shell
sudo npm i --global hostname-natural-order
`$3
`shell
hostname-natural-order microsoft.com example.org google.com
`It will print:
`
google.com
microsoft.com
example.org
`This program can also read hostname list from file. Just pipe "cat" output.
`shell
cat hostnames.txt | hostname-natural-order
``Unexpected results might be happen if you don't validate the input.
See unit test files for what we've test.
It required node.js version > 16.x because we use ip-toolkit
who has requirement of node.js > 16.x. If you need to run it on older version of node.js, please raise an issue
so I can know demand for that exists.