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 else、Number 部分に構造体も必要ありません。代わりに、単純に差を返すことができます

    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 に答える