natural-compare
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
Natural-compare is a powerful JavaScript tool that allows developers to compare strings containing a mix of letters and numbers in the way a human being would in sort order, described as a "natural ordering". It helps to ensure your data is sorted in a way that makes intuitive sense to a human reader, making your application's user interface smoother and more user-friendly.
One of the advantages of natural-compare is its ease of use. If you want to use this tool in the browser, simply include the following line in your HTML script tag:
<script src=min.natural-compare.js></script>
For use in node.js you can install it via npm with the following command:
npm install natural-compare-lite
and then require the package in your JavaScript file with:
require("natural-compare-lite")
Once the set-up is complete, you can start sorting strings in a naturally ordered way.
var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
a.sort(String.naturalCompare);
// This will output
// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]
Case-insensitive sorting can be achieved via a wrapper function:
a.sort(function(a, b){
return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
});
It also works well with arrays of objects, and allows for additional capabilities like sorting by multiple properties, and pre-transforming keys for more efficient comparison:
var a = [ {"make":"Audi", "model":"A6"}
, {"make":"Kia", "model":"Rio"} ];
// sort by make, then by model
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);
})
This tool also supports international languages and alphabets:
// Russian alphabet
String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
["Ё", "А", "Б"].sort(String.naturalCompare)
// This will output
// ["А", "Б", "Ё"]
The documentation of natural-compare can be found in its GitHub repository: https://github.com/litejs/natural-compare-lite. Here, you'll find examples of how to use the tool, various edge cases and caveats, as well as guidelines on how to contribute to its development.