What is @discoveryjs/natural-compare?
@discoveryjs/natural-compare is an npm package that provides a natural order string comparison algorithm. This is particularly useful for sorting strings in a way that humans would expect, such as sorting file names, version numbers, or any other strings that contain numbers.
What are @discoveryjs/natural-compare's main functionalities?
Basic Natural Comparison
This feature allows you to sort an array of strings in a natural order. In the example, file names are sorted in a way that a human would expect, with 'file10.txt' coming after 'file2.txt'.
const naturalCompare = require('@discoveryjs/natural-compare');
const arr = ['file10.txt', 'file2.txt', 'file1.txt'];
arr.sort(naturalCompare);
console.log(arr); // Output: ['file1.txt', 'file2.txt', 'file10.txt']
Case Insensitive Comparison
This feature allows you to perform a case-insensitive natural comparison. By converting all strings to lowercase before comparison, the sorting ignores case differences.
const naturalCompare = require('@discoveryjs/natural-compare');
const arr = ['File10.txt', 'file2.txt', 'file1.txt'];
arr.sort((a, b) => naturalCompare(a.toLowerCase(), b.toLowerCase()));
console.log(arr); // Output: ['file1.txt', 'file2.txt', 'File10.txt']
Other packages similar to @discoveryjs/natural-compare
natural-orderby
natural-orderby is another npm package that provides natural sorting for arrays of objects and strings. It offers more flexibility by allowing you to specify the property to sort by in an array of objects. Compared to @discoveryjs/natural-compare, it is more feature-rich but also more complex to use.
string-natural-compare
string-natural-compare is a lightweight npm package for natural string comparison. It is similar to @discoveryjs/natural-compare in terms of functionality but is less popular and has fewer features. It is a good alternative if you need a simple and small library for natural string comparison.
@discoveryjs/natural-compare
Compare strings in a natural order
Install
npm install @discoveryjs/natural-compare
Usage
import { naturalCompare } from '@discoveryjs/natural-compare';
[
'file10.js',
'file1.js',
'file2.js',
'file12.js',
'file9.js'
].sort(naturalCompare);
[
'file10.js',
'file1.js',
'file2.js',
'file12.js',
'file9.js'
].sort();
In browser:
<script type="module">
import { natualCompare } from "@discoveryjs/natural-compare/dist/natural-compare.esm.js";
array.sort(naturalCompare);
</script>
<script src="@discoveryjs/natural-compare/dist/natural-compare.js"></script>
<script>
array.sort(naturalCompare);
</script>
License
MIT