What is string-natural-compare?
The string-natural-compare npm package provides a way to compare strings in a human-friendly manner, often referred to as 'natural order' comparison. This is particularly useful for sorting lists of strings that include numbers, where you want the numbers to be sorted in numerical order rather than lexicographical order.
What are string-natural-compare's main functionalities?
Basic Natural Comparison
This feature allows you to compare two strings in a natural order. In this example, 'file10' is compared to 'file2', and the result is 1, indicating that 'file10' comes after 'file2' in natural order.
const naturalCompare = require('string-natural-compare');
const result = naturalCompare('file10', 'file2');
console.log(result); // Output: 1
Sorting an Array
This feature allows you to sort an array of strings in natural order. In this example, the array ['file10', 'file2', 'file1'] is sorted to ['file1', 'file2', 'file10'].
const naturalCompare = require('string-natural-compare');
const files = ['file10', 'file2', 'file1'];
files.sort(naturalCompare);
console.log(files); // Output: ['file1', 'file2', 'file10']
Case-Insensitive Comparison
This feature allows you to perform a case-insensitive natural comparison. In this example, 'File10' is compared to 'file2' with case insensitivity, and the result is 1, indicating that 'File10' comes after 'file2' in natural order.
const naturalCompare = require('string-natural-compare');
const result = naturalCompare('File10', 'file2', { caseInsensitive: true });
console.log(result); // Output: 1
Other packages similar to string-natural-compare
natural-compare-lite
The natural-compare-lite package provides similar functionality for natural order string comparison but is designed to be a lighter and faster alternative. It lacks some of the additional options available in string-natural-compare, such as case insensitivity.
alphanum-sort
The alphanum-sort package offers alphanumeric sorting of arrays, which is similar to natural order comparison. It is optimized for performance and can handle large arrays efficiently. However, it does not provide as many customization options as string-natural-compare.
String Natural Compare
Compare alphanumeric strings the same way a human would, using a natural order algorithm
Standard sorting: Natural order sorting:
img1.png img1.png
img10.png img2.png
img12.png img10.png
img2.png img12.png
This module makes two functions available on the global String
object:
String.naturalCompare
(case-sensitive)String.naturalCaseCompare
(case-insensitive)
These functions return a number indicating whether one string should come before, after, or is the same as another string.
They can be easily used with the native .sort()
array method.
Fast and Robust
This module uses an extremely performant and robust algorithm to compare alphanumeric strings. It does not convert numeric substrings into JavaScript numbers, so it can compare strings containing very large numeric substrings (i.e. exceeding what can be contained in a 64-bit integer). The algorithm has been optimized to be very fast, even when a custom alphabet has been configured.
Installation
Node.js:
npm install string-natural-compare --save
Then in your JS:
require('string-natural-compare');
Bower:
bower install string-natural-compare
Include the script in your HTML (drop the ".min" to use the development version):
<script src="/bower_components/string-natural-compare/dist/natural-compare.min.js"></script>
Note: IE8 and lower not supported.
Download:
Production and development versions can be found here and can be included in your page similar to the HTML example above.
Usage
var a = ['z1.doc', 'z10.doc', 'z17.doc', 'z2.doc', 'z23.doc', 'z3.doc'];
a.sort(String.naturalCompare);
var a = ['B', 'C', 'a', 'd'];
a.sort(String.naturalCaseCompare);
String.naturalCompare(
'1165874568735487968325787328996865',
'1165874568735487968325787328996864'
);
var a = [
{street: '350 5th Ave', room: 'A-1021'},
{street: '350 5th Ave', room: 'A-21046-b'}
];
a.sort(function(a, b) {
return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room);
});
var a = [
{make: 'Audi', model: 'R8'},
{make: 'Porsche', model: '911 Turbo S'}
];
a = a.map(function(car) {
car.sort_key = (car.make + ' ' + car.model).toLowerCase();
});
a.sort(function(a, b) {
return String.naturalCompare(a.sort_key, b.sort_key);
});
Custom Alphabet
It is possible to configure a custom alphabet to achieve a desired character ordering.
String.alphabet = 'ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy';
['t', 'z', 'x', 'õ'].sort(String.naturalCompare);
String.alphabet = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя';
['Ё', 'А', 'Б'].sort(String.naturalCompare);
Note: Putting numbers in the custom alphabet can cause undefined behaviour.