排序数组元素(带数字的字符串),自然排序 [英] Sort Array Elements (string with numbers), natural sort
本文介绍了排序数组元素(带数字的字符串),自然排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的数组;
I have an array like;
["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]
需要对它进行排序,看起来像是这样;
And need to sort it so it appears like;
["IL0 Foo", "IL3 Bob says hello", "IL10 Baz", "PI0 Bar"]
我尝试过排序功能;
function compare(a,b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
但这会给出订单
["IL0 Foo", "IL10 Baz", "IL3 Bob says hello", "PI0 Bar"]
我试过想一个可行的正则表达式,但无法理解它。
如果它有助于格式化总是2个字母,x个数字,然后是任意数量的字符。
I have tried to think of a regex that will work but can't get my head around it.
If it helps the format will always be 2 letters, x amount of numbers, then any number of characters.
推荐答案
这称为自然排序,可以在JS中实现如下:
This is called "natural sort" and can be implemented in JS like this:
function naturalCompare(a, b) {
var ax = [], bx = [];
a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
while(ax.length && bx.length) {
var an = ax.shift();
var bn = bx.shift();
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if(nn) return nn;
}
return ax.length - bx.length;
}
/////////////////////////
test = [
"img12.png",
"img10.png",
"img2.png",
"img1.png",
"img101.png",
"img101a.png",
"abc10.jpg",
"abc10",
"abc2.jpg",
"20.jpg",
"20",
"abc",
"abc2",
""
];
test.sort(naturalCompare)
document.write("<pre>" + JSON.stringify(test,0,3));
要按相反顺序排序,只需交换参数:
To sort in reverse order, just swap the arguments:
test.sort(function(a, b) { return naturalCompare(b, a) })
或只是
test = test.sort(naturalCompare).reverse();
这篇关于排序数组元素(带数字的字符串),自然排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文