显示以特定格式排列的数组

时间:2013-08-19 14:33:46

标签: javascript arrays

我在JavaScript中有以下数组:

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

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

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

我怎么能这样做?

4 个答案:

答案 0 :(得分: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 = lu9b = 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

答案 1 :(得分: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"]

答案 2 :(得分: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);

答案 3 :(得分: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"

继承人Fiddle