@version 1.4.0
@date 2015-10-26
@stability 3 - Stable
〇自然比较

比较包含字母和数字混合的字符串 就像人类按照排序顺序一样。 这被称为“自然排序”。
Standard sorting: Natural order sorting:
img1.png img1.png
img10.png img2.png
img12.png img10.png
img2.png img12.png
字符串。naturalCompare返回一个数字,表示 引用字符串是在前面还是后面,还是相同 作为给定字符串的排序顺序。 与内置的sort()函数一起使用。
安装
- 在浏览器
<script src=min.natural-compare.js></script>
- 在node . js:
npm install natural-compare-lite
require("natural-compare-lite")
用法
// Simple case sensitive example
var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"];
a.sort(String.naturalCompare);
// ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"]
// Use wrapper function for case insensitivity
a.sort(function(a, b){
return String.naturalCompare(a.toLowerCase(), b.toLowerCase());
})
// In most cases we want to sort an array of objects
var a = [ {"street":"350 5th Ave", "room":"A-1021"}
, {"street":"350 5th Ave", "room":"A-21046-b"} ];
// sort by street, then by room
a.sort(function(a, b){
return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room);
})
// When text transformation is needed (eg toLowerCase()),
// it is best for performance to keep
// transformed key in that object.
// There are no need to do text transformation
// on each comparision when sorting.
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);
})
- 可以很好地处理ISO格式的日期,例如“Rev 2012-07-26.doc”。
定制的字母
可以配置自定义字母 达到所期望的顺序。
// Estonian alphabet
String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy"
["t", "z", "x", "õ"].sort(String.naturalCompare)
// ["z", "t", "õ", "x"]
// Russian alphabet
String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя"
["Ё", "А", "Б"].sort(String.naturalCompare)
// ["А", "Б", "Ё"]
外部链接
执照
版权所有(c) 2012-2015 Lauri Rooden <[email protected]>
麻省理工学院许可证