gpt4 book ai didi

javascript - 对数字和字母元素的数组进行排序(自然排序)

转载 作者:可可西里 更新时间:2023-11-01 02:13:33 26 4
gpt4 key购买 nike

假设我有一个数组

var arr = [1,5,"ahsldk",10,55,3,2,7,8,1,2,75,"abc","huds"];

然后我尝试对其进行排序,我得到类似...

[1, 1, 10, 2, 2, 3, 5, 55, 7, 75, 8, "abc", "ahsldk", "huds"]

注意10在2之前,我怎么能有更像的东西

[1,1,2,2,3,5 ..., "abc", "ahs...",...]

最佳答案

来自 http://snipplr.com/view/36012/javascript-natural-sort/作者:

Array.prototype.naturalSort= function(){
var a, b, a1, b1, rx=/(\d+)|(\D+)/g, rd=/\d+/;
return this.sort(function(as, bs){
a= String(as).toLowerCase().match(rx);
b= String(bs).toLowerCase().match(rx);
while(a.length && b.length){
a1= a.shift();
b1= b.shift();
if(rd.test(a1) || rd.test(b1)){
if(!rd.test(a1)) return 1;
if(!rd.test(b1)) return -1;
if(a1!= b1) return a1-b1;
}
else if(a1!= b1) return a1> b1? 1: -1;
}
return a.length- b.length;
});
}

或者,来自 Alphanum:Javascript Natural Sorting Algorithm by Brian Huisman :

Array.prototype.alphanumSort = function(caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z] = [];
var x = 0, y = -1, n = 0, i, j;

while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z][++y] = "";
n = m;
}
this[z][y] += j;
}
}

this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else return (aa > bb) ? 1 : -1;
}
}
return a.length - b.length;
});

for (var z = 0; z < this.length; z++)
this[z] = this[z].join("");
}

关于javascript - 对数字和字母元素的数组进行排序(自然排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4373018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com