1

我想对这条记录进行排序,我的输入数组是 a1

var a1 = ["ap1","ap10","ap11","ap2","ap3","ap4","ap5","ap6","ap7","ap8","ap9"];

输出应该是这样的:

["ap1","ap2","ap3","ap4","ap5","ap6","ap7","ap8","ap9","ap10","ap11"];

这是代码,

    var a1 = ["ap1","ap10","ap11","ap2","ap3","ap4","ap5","ap6","ap7","ap8","ap9"];

    var a2 = a1.sort(function(a,b){
    var charPart = [a.substring(0,1), b.substring(0,1)],
    numPart = [a.substring(1)*1, b.substring(1)*1];

    if(charPart[0] < charPart[1]) return -1;
        else if(charPart[0] > charPart[1]) return 1;
        else{ //(charPart[0] == charPart[1]){
            if(numPart[0] < numPart[1]) return -1;
            else if(numPart[0] > numPart[1]) return 1;
            return 0;
        }
    });

    alert(a2.toString());
4

4 回答 4

2
var charPart = [a.substring(0,1), b.substring(0,1)],
numPart = [a.substring(1)*1, b.substring(1)*1];

您似乎忘记了字符串的char 部分是2 个字符长 :-) 对于更通用的解决方案,您可能会使用类似apN

var charPart = [a.match(/^\D*/)[0], b.match(/^\D*/)[0]],
    numPart = [+a.replace(/^\D*/, ''), +b.replace(/^\D*/, '')];
于 2013-03-26T12:56:31.323 回答
1
var a1 = ["ap1","ap10","ap11","ap2","ap3","ap4","ap5","ap6","ap7","ap8","ap9","ap9", "ap9"];

var a2 = a1.sort(function (a, b) {
    return parseInt(a.replace("ap", ""), 10) - parseInt(b.replace("ap", ""), 10);
});

alert(a2);

http://jsfiddle.net/dQD9F/

于 2013-03-26T13:01:03.613 回答
0

试试这个:

var a2 = a1.sort(function(a, b) {
   if (a == b) {
      return 0;
   }

   var charParts = [a.replace(/[0-9]/g, ''), b.replace(/[0-9]/g, '')],
       numParts = [parseInt(a.replace(/[^0-9]/g, ''), 10), parseInt(b.replace(/[^0-9]/g, ''), 10)];

   if (charParts[0] != charParts[1]) {
       return charParts[0] > charParts[1] ? 1 : -1;
   }

   return numParts[0] > numParts[1] ? 1 : -1;
});
于 2013-03-26T13:02:08.230 回答
0

除了 Bergis Answer 之外,if elseNumber 部分也不需要构造。您可以改为简单地返回差异

    var a2 = a1.sort(function (a, b) {
        var charPart = [a.match(/^\D*/)[0], b.match(/^\D*/)[0]],
            numPart = [+a.replace(/^\D*/, ''), +b.replace(/^\D*/, '')];
        if (charPart[0] < charPart[1]) return -1;
        if (charPart[0] > charPart[1]) return 1;
        return numPart[0] - numPart[1]
    });

更新:

var a1 = ["a3p1", "a4p2", "ap8a1", "a8p10", "a4p10", "ap8a4", "a8p11", "a9p2", "ap3", "ap4", "ap5", "ap6", "ap7", "ap8", "ap9"];
var a2 = a1.sort(function (a, b) {
    var _a = a.split(/(\d+)/);
    var _b = b.split(/(\d+)/);
    var len = Math.min(_a.length, _b.length);
    for (var i = 0; i < len - 1; i++) {
        var c = +_a[i],
            d = +_b[i];
        if (c===c) _a[i] = c;
        if (d===d) _b[i] = d;
        if (_a[i] !== _b[i]) {
            return _a[i] > _b[i] ? 1 : -1;
        }
    }
    return (_a.length - _b.length);
});
console.log(a2); //["a3p1", "a4p2", "a4p10", "a8p10", "a8p11", "a9p2", "ap3", "ap4", "ap5", "ap6", "ap7", "ap8", "ap8a1", "ap8a4", "ap9"]

这是一个关于JSBin的示例: 这对数组进行排序,考虑到所有数字部分

于 2013-03-26T13:02:25.760 回答