2 [Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png
3 [Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png
4 [1]: https://travis-ci.org/litejs/natural-compare-lite
5 [2]: https://coveralls.io/r/litejs/natural-compare-lite
6 [npm package]: https://npmjs.org/package/natural-compare-lite
7 [GitHub repo]: https://github.com/litejs/natural-compare-lite
16 Natural Compare – [![Build][]][1] [![Coverage][]][2]
19 Compare strings containing a mix of letters and numbers
20 in the way a human being would in sort order.
21 This is described as a "natural ordering".
24 Standard sorting: Natural order sorting:
31 String.naturalCompare returns a number indicating
32 whether a reference string comes before or after or is the same
33 as the given string in sort order.
34 Use it with builtin sort() function.
43 <script src=min.natural-compare.js></script>
46 - In node.js: `npm install natural-compare-lite`
49 require("natural-compare-lite")
55 // Simple case sensitive example
56 var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
57 a.sort(String.naturalCompare);
58 // ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]
60 // Use wrapper function for case insensitivity
61 a.sort(function(a, b){
62 return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
65 // In most cases we want to sort an array of objects
66 var a = [ {"street":"350 5th Ave", "room":"A-1021"}
67 , {"street":"350 5th Ave", "room":"A-21046-b"} ];
69 // sort by street, then by room
70 a.sort(function(a, b){
71 return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room);
74 // When text transformation is needed (eg toLowerCase()),
75 // it is best for performance to keep
76 // transformed key in that object.
77 // There are no need to do text transformation
78 // on each comparision when sorting.
79 var a = [ {"make":"Audi", "model":"A6"}
80 , {"make":"Kia", "model":"Rio"} ];
82 // sort by make, then by model
84 car.sort_key = (car.make + " " + car.model).toLowerCase();
86 a.sort(function(a, b){
87 return String.naturalCompare(a.sort_key, b.sort_key);
91 - Works well with dates in ISO format eg "Rev 2012-07-26.doc".
96 It is possible to configure a custom alphabet
97 to achieve a desired order.
101 String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy"
102 ["t", "z", "x", "õ"].sort(String.naturalCompare)
103 // ["z", "t", "õ", "x"]
106 String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
107 ["Ё", "А", "Б"].sort(String.naturalCompare)
115 - [GitHub repo][https://github.com/litejs/natural-compare-lite]
116 - [jsperf test](http://jsperf.com/natural-sort-2/12)
122 Copyright (c) 2012-2015 Lauri Rooden <lauri@rooden.ee>
123 [The MIT License](http://lauri.rooden.ee/mit-license.txt)