3

我在 JavaScript 中有以下数组:

myArray = ["lu9","lu10","lu11","ma9","ma10","ma11","mi9","mi10","mi11"];

然后,我需要显示值(例如在警报中)但必须按如下方式排列:

"lu9,ma9,mi9,lu10,ma10,mi10,lu11,ma11,mi11"

我怎么能做到这一点?

4

4 回答 4

3

列表中的每个项目都包含两部分:前导字符混杂(mi、ma、lu)和数字后缀。为了正确排序,我们必须将两者都考虑在内。

array.sort(function sorter (a, b) {
    var re = /^(\D+)(\d+)$/,
        left = re.exec(a),
        right = re.exec(b);

    if (left[1] === right[1]) {
        return Number(left[2]) - Number(right[2]);
    }

    return left[1] < right[1] ? -1 : 1;
});

假设a = lu9b = lu10

1. left = ['lu9', 'lu', '9']
2. right = ['lu10', 'lu', '10']
3. left[1] === right[1]
   1. Number(left[2]) = 9
   2. Number(right[2]) = 10
   3. return 9 - 10 (negative number, a before b)

现在如果我们的输入是a = lu9and b = mi4

1. left = ['lu9', 'lu', '9']
2. right = ['mi4', 'mi', '4']
3. left[1] !== right[1]
   1. left[1] < right[1] = true
   2. return -1
于 2013-08-19T15:41:28.927 回答
2

我们需要先按数字排序,然后按字母排序。这里不需要正则表达式。

我们将使用填充:

so ma11 will be 0011ma
and mi11 will be 0011mi
and ma11 will be 0011ma

(and mi9 will be 0009mi , the padding helps 11 to be bigger then 2 as string)

所以现在对其进行排序 - 将产生正确的结果。

var a = ["ma9", "ma10", "ma11", "mi9", "mi10", "mi11", "lu9", "lu10", "lu11"]
a.sort(function (a, b)
{
        return   calc(a) > calc(b);
});

function calc(x)
{
    return ("0000" + x.slice(2)).slice(-4) + x.slice(0,2);
}

结果 :

    ["ma9", "ma10", "ma11", "mi9", "mi10", "mi11", "lu9", "lu10", "lu11"]
于 2013-08-19T14:38:26.403 回答
2
var myArray = ["lu9","lu10","lu11","ma9","ma10","ma11","mi9","mi10","mi11"];

var derp = function(a, b) {
    a = a.replace(/[^0-9]+/g, '', a);
    b = b.replace(/[^0-9]+/g, '', b);
    return a < b;
}

myArray.sort(derp);
于 2013-08-19T14:38:50.573 回答
2
var myArray = ["lu9", "lu10", "lu11", "ma9", "ma10", "ma11", "mi9", "mi10", "mi11"];

function myResult(myArray) {
    myArray = myArray.slice().sort(function (a, b) {
        var reg = /\d+/ //A regex to extract the numerical part
        var num = 2 * (+a.match(reg) - +b.match(reg)) //Put a weight of 2 on the numerical value
        var str = a > b ? 1 : a < b ? -1 : 0 //The strings value with a single weight
        return num + str //add them and we have a positive or negative value with a correct weight on the numerical part
    })
    return "" + myArray

}

console.log (myResult(myArray)) //"lu9,ma9,mi9,lu10,ma10,mi10,lu11,ma11,mi11"

这是一个小提琴

于 2013-08-19T14:48:05.990 回答