@version 0.4.5
@date 2014-01-21
@stability 2 - Unstable
Natural Compare –
Compare strings containing a mix of letters and numbers
in the way a human being would in sort order.
This is described as a "natural ordering".
Standard sorting: Natural order sorting:
img1.png img1.png
img10.png img2.png
img12.png img10.png
img2.png img12.png
String.naturalCompare returns a number indicating
whether a reference string comes before or after or is the same
as the given string in sort order.
Use it with builtin sort() function.
Download compressed
(310 bytes, 236 bytes gzipped)
or uncompressed source.
Installation
<script src=min.natural-compare.js></script>
- In node.js:
npm install natural-compare-lite
require("natural-compare-lite")
Usage
var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
a.sort(String.naturalCompare);
a.sort(function(a, b){
return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
})
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":"A6"}
, {"make":"Kia", "model":"Rio"} ];
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);
})
- Removes leading zeros so "a 1" and "a 001" are equal.
- Works well with dates in ISO format eg "Rev 2012-07-26.doc".
Browser Support
External links
Licence
Copyright (c) 2012, 2014 Lauri Rooden <lauri@rooden.ee>
The MIT License