javascript - 对数组元素(带有数字的字符串)进行排序,自然排序

标签 javascript jquery sorting

我有一个像这样的数组;

["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]

并且需要对其进行排序,使其看起来像;

["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 个数字,然后是任意数量的字符。

最佳答案

这称为“自然排序”,可以在 JS 中实现,如下所示:

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));

要按相反顺序排序,只需交换参数即可:

test.sort(function(a, b) { return naturalCompare(b, a) })

或者简单地

test = test.sort(naturalCompare).reverse();

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

相关文章:

javascript - 滚动到 div 顶部

javascript - AJAX 传递变量问题

javascript - 使用post方法将值从一个html传递到另一个html

javascript - 如何更改动态生成的文本框的颜色

java - 使用比较器对 Java TreeSet 进行排序

javascript - 这条语句 "Object.prototype"是做什么的?

javascript - 如何根据用户指定的时间填充一个100%的进度条

javascript - 允许在 Firestore 中更新特定的嵌套值

php - mysql中的order by应该与excel中的sorted相同吗?

python - 如何对文本文件的内容进行排序