具有混合类型值的数组的JavaScript排序

时间:2014-05-06 11:31:45

标签: javascript jquery

我有以下数组需要按降序进行数字排序:

var arr = ['5', '5.1', '5.1.4', '6.0.0', '500'];

所需的顺序如下:

500
6.0.0
5.1.4
5.1
5

然而,我尝试的所有方法似乎都没有给出所需的结果。这种排序函数的一个例子,它不能使用这种数组:

arr = arr.sort(function(a,b){return b - a});

有人可以告诉我如何实现这一目标吗?

感谢。

2 个答案:

答案 0 :(得分:0)

以下解决方案的逻辑完全来自this answer (所有信用都在那里!)但是结果被反转以使顺序降序(+修复小错误):

['5', '5.1', '5.1.4', '6.0.0', '500'].sort(function(a, b) {
    if (a === b) {
       return 0;
    }

    var a_components = a.split('.'),
        b_components = b.split('.'),
        len = Math.min(a_components.length, b_components.length);

    for (var i = 0; i < len; i++) {
        if (parseInt(a_components[i], 10) > parseInt(b_components[i], 10)) {
            return -1;
        }

        if (parseInt(a_components[i], 10) < parseInt(b_components[i], 10)) {
            return 1;
        }
    }

    if (a_components.length > b_components.length) {
        return -1;
    }

    if (a_components.length < b_components.length) {
        return 1;
    }

    return 0;
});

// >> ["500", "6.0.0", "5.1.4", "5.1", "5"]

答案 1 :(得分:0)

arr.sort(function(a,b){

    //if they are equal, return 0
    if(a==b) return 0;

    //split version numbers and compare each one until we got one that differs
    var verA = a.split('.'), verB = b.split('.');
    for(var i=0;i<Math.max(verA.length, verB.length);i++) {
        //verA is shorter or equal, so we return 1
        if(verA[i]===undefined)
            return 1;
        //verB is shorter or equal, so we return -1
        if(verB[i]===undefined)
            return -1;

        //first encounter where the 2 are defined and are different
        if(verB[i]-verA[i]!=0)
            return verB[i]-verA[i];

        //in other situations they are equal, so we go to the next iteration
    }

});