繁体   English   中英

按预期顺序对字符串进行排序

[英]Sort the strings in intended order

我有字符串数组

sample0
sample1
sample11
sample12
sample13
sample14
sample2
sample21
sample3

但是我需要这样。 我不知道解决方案。 前缀可能不会一直采样。

sample0
sample1
sample2
sample3
sample11
sample12
sample13
sample14
sample21

使用正则表达式/\\d+$/可以将字符串末尾显示的数字与Array的sort()进行匹配,如下所示:

 var strArr = ['sample0', 'sample1', 'sample11', 'sample12', 'sample13', 'sample14', 'sample2', 'sample21', 'sample3']; var strRes = strArr.sort(function(a, b){ return a.match(/\\d+$/) - b.match(/\\d+$/); }) console.log(strRes); 

注意:这只会从末尾提取数字,并将根据该数字进行排序。

解决方案1:

var arr = ['sample0', 'sample1', 'sample11', 'sample12', 'sample13', 'sample14', 'sample2', 'sample21', 'sample3']
arr.sort(function (a, b) {
    return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});
console.log(arr);

localeCompare()方法返回一个数字,该数字指示参考字符串是按排序顺序位于给定字符串之前还是之后还是与之相同。

参考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

解决方案2:

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

arr.sort(naturalCompare);
console.log(arr);

此解决方案来自https://stackoverflow.com/a/15479354/3910232

如果前缀“ sample”是常量,则

   var numString=['sample1','sample12','sample123','sample2','sample0','sample23'];

    var num=new Array(numString.length); 
    for (var i = 0; i < numString.length; i++) {
    num[i]=numString[i].substring(6);
    }
    var st=numString[0].substring(0,6);
    num.sort();
    var ne=(st + num.join(';' + st)).split(';');
    alert(ne);

智能排序包可以完成此任务。 我确定还有其他解决方案。 查找关键字“自然排序”和“智能排序”。

var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['sample1', 'sample12', 'sample3'];
myArray.sort(collator.compare);

试试看

 var array = ['sample0','sample1','sample11','sample12','sample13', 'sample14','sample2','sample21','sample3'] var sortedArray = array.sort(function(a, b){ var regXStr = /[^a-zA-Z]/g, regXNum = /[^0-9]/g; var aStr = a.replace(regXStr, "").toLowerCase(); var bStr = b.replace(regXStr, "").toLowerCase(); if(aStr === bStr) { var aNum = parseInt(a.replace(regXNum, ""), 10); var bNum = parseInt(b.replace(regXNum, ""), 10); return aNum === bNum ? 0 : aNum > bNum ? 1 : -1; } else { return aStr > bStr ? 1 : -1; } }); console.log(sortedArray) 

暂无
暂无

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

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