简体   繁体   English

排序数组元素(带数字的字符串),自然排序

[英]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"]

I have tried a sort function;我尝试了排序功能;

function compare(a,b) {
  if (a < b)
     return -1;
  if (a > b)
    return 1;
  return 0;
}

but this gives the order但这给出了命令

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

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.如果有帮助,格式将始终是 2 个字母、x 数量的数字,然后是任意数量的字符。

This is called "natural sort" and can be implemented in JS like this:这称为“自然排序”,可以像这样在 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));

To sort in reverse order, just swap the arguments:要以相反的顺序排序,只需交换参数:

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

or simply或者干脆

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

You could use String#localeCompare with options您可以将String#localeCompareoptions

sensitivity灵敏度

Which differences in the strings should lead to non-zero result values.字符串中的哪些差异应导致非零结果值。 Possible values are:可能的值为:

  • "base" : Only strings that differ in base letters compare as unequal. "base" :只有基本字母不同的字符串比较为不相等。 Examples: a ≠ b , a = á , a = A .示例: a ≠ ba = áa = A
  • "accent" : Only strings that differ in base letters or accents and other diacritic marks compare as unequal. "accent" :只有在基本字母或重音和其他变音符号方面不同的字符串比较为不相等。 Examples: a ≠ b , a ≠ á , a = A .示例: a ≠ ba ≠ áa = A
  • "case" : Only strings that differ in base letters or case compare as unequal. "case" : 只有基字母不同或大小写不同的字符串比较为不相等。 Examples: a ≠ b , a = á , a ≠ A .示例: a ≠ ba = áa ≠ A
  • "variant" : Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. "variant" :基本字母、重音和其他变音符号不同的字符串,或大小写比较为不相等的字符串。 Other differences may also be taken into consideration.也可以考虑其他差异。 Examples: a ≠ b , a ≠ á , a ≠ A .示例: a ≠ ba ≠ áa ≠ A

The default is "variant" for usage "sort";使用“排序”的默认值是“变体”; it's locale dependent for usage "search".它取决于使用“搜索”的语言环境。

numeric数字

Whether numeric collation should be used, such that "1" < "2" < "10".是否应使用数字排序规则,例如“1”<“2”<“10”。 Possible values are true and false ;可能的值为truefalse the default is false .默认值为false This option can be set through an options property or through a Unicode extension key;这个选项可以通过 options 属性或通过 Unicode 扩展键设置; if both are provided, the options property takes precedence.如果两者都提供,则options属性优先。 Implementations are not required to support this property.不需要实现来支持此属性。

 var array = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"]; array.sort(function (a,b) { return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }); }); console.log(array);

var re = /([a-z]+)(\d+)(.+)/i;
var arr = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"];
var order = arr.sort( function(a,b){
    var ma = a.match(re),
        mb = b.match(re),
        a_str = ma[1],
        b_str = mb[1],
        a_num = parseInt(ma[2],10),
        b_num = parseInt(mb[2],10),
        a_rem = ma[3],
        b_rem = mb[3];
    return a_str > b_str ? 1 : a_str < b_str ? -1 : a_num > b_num ? 1 : a_num < b_num ? -1 : a_rem > b_rem;  
});

I liked georg's solution a lot, but I needed underscores ("_") to sort before numbers.我非常喜欢 georg 的解决方案,但我需要下划线(“_”)在数字之前进行排序。 Here's how I modified his code:这是我修改他的代码的方法:

 var chunkRgx = /(_+)|([0-9]+)|([^0-9_]+)/g; function naturalCompare(a, b) { var ax = [], bx = []; a.replace(chunkRgx, function(_, $1, $2, $3) { ax.push([$1 || "0", $2 || Infinity, $3 || ""]) }); b.replace(chunkRgx, function(_, $1, $2, $3) { bx.push([$1 || "0", $2 || Infinity, $3 || ""]) }); while(ax.length && bx.length) { var an = ax.shift(); var bn = bx.shift(); var nn = an[0].localeCompare(bn[0]) || (an[1] - bn[1]) || an[2].localeCompare(bn[2]); 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", "_abc", "_ab_c", "_ab__c", "_abc_d", "ab_", "abc_", "_ab_cd", "" ]; test.sort(naturalCompare) document.write("<pre>" + JSON.stringify(test,0,3));

Pad numbers in string with leading zeros, then sort normally.用前导零填充字符串中的数字,然后正常排序。

 var naturalSort = function (a, b) { a = ('' + a).replace(/(\\d+)/g, function (n) { return ('0000' + n).slice(-5) }); b = ('' + b).replace(/(\\d+)/g, function (n) { return ('0000' + n).slice(-5) }); return a.localeCompare(b); } var naturalSortModern = function (a, b) { return ('' + a).localeCompare(('' + b), 'en', { numeric: true }); } console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSort))); console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSortModern)));

You could do a regex like this to get non-numeric and numeric parts of the string:您可以执行这样的正则表达式来获取字符串的非数字和数字部分:

var s = "foo124bar23";
s.match(/[^\d]+|\d+/g)

returns: ["foo", "124" , "bar" , "23"]返回: ["foo", "124" , "bar" , "23"]

Then in your compare function you can iterate through the parts of the two strings comparing them part-by-part.然后在您的比较函数中,您可以遍历两个字符串的各个部分,逐个比较它们。 The first non-matching part determines the result of the overall comparison.第一个不匹配的部分决定了整体比较的结果。 For each part, check if the part starts with a digit and if so parse it as a number before doing the comparison.对于每个部分,检查该部分是否以数字开头,如果是,则在进行比较之前将其解析为数字。

Add one more alternative (why not):添加另一种选择(为什么不呢):

var ary = ["IL0 Foo", "PI0 Bar", "IL10 Hello", "IL10 Baz", "IL3 Bob says hello"];

// break out the three components in to an array
// "IL10 Bar" => ['IL', 10, 'Bar']
function getParts(i){
    i = i || '';
    var parts = i.match(/^([a-z]+)([0-9]+)(\s.*)$/i);
    if (parts){
        return [
            parts[1],
            parseInt(parts[2], 10),
            parts[3]
        ];
    }
    return []; // erroneous
}
ary.sort(function(a,b){
    // grab the parts
    var _a = getParts(a),
        _b = getParts(b);

    // trouble parsing (both fail = no shift, otherwise
    // move the troubles element to end of the array)
    if(_a.length == 0 && _b.length == 0) return 0;
    if(_a.length == 0) return -1;
    if(_b.length == 0) return 1;

    // Compare letter portion
    if (_a[0] < _b[0]) return -1;
    if (_a[0] > _b[0]) return 1;
    // letters are equal, continue...

    // compare number portion
    if (_a[1] < _b[1]) return -1;
    if (_a[1] > _b[1]) return 1;
    // numbers are equal, continue...

    // compare remaining string
    if (_a[2] < _b[2]) return -1;
    if (_a[2] > _b[2]) return 1;
    // strings are equal, continue...

    // exact match
    return 0;
});

jsfiddle example jsfiddle 示例

Not pretty, but check the first two char codes.不漂亮,但请检查前两个字符代码。 If all equal parse and compare the numbers:如果所有相等的解析和比较数字:

var arr = ["IL0 Foo", "IL10 Baz", "IL3 Bob says hello", "PI0 Bar"];
arr.sort(function (a1, b1) {
    var a = parseInt(a1.match(/\d+/g)[0], 10),
        b = parseInt(b1.match(/\d+/g)[0], 10),
        letterA = a1.charCodeAt(0),
        letterB = b1.charCodeAt(0),
        letterA1 = a1.charCodeAt(1),
        letterB1 = b1.charCodeAt(1);
    if (letterA > letterB) {
        return 1;
    } else if (letterB > letterA) {
        return -1;
    } else {
        if (letterA1 > letterB1) {
            return 1;
        } else if (letterB1 > letterA1) {
            return -1;
        }
        if (a < b) return -1;
        if (a > b) return 1;
        return 0;
    }
});

Example例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM