多排序多维数组

时间:2012-02-21 08:49:51

标签: javascript jquery

var availableTags = [
    {value:"fruit",desc:"fruit",groupId:2,userId:4},
    {value:"aGan",desc:"normal user",groupId:4,userId:5},
    {value:"father's home ",desc:"normal user",groupId:2,userId:4}     

  ].sort(function(a, b) {  return a.groupId > b.groupId; });

groupId字段排序,但如何按groupIdvalue排序?

4 个答案:

答案 0 :(得分:7)

将return语句更改为

return a.groupId > b.groupId || (a.groupId == b.groupId && a.value > b.value);

答案 1 :(得分:2)

怎么样

.sort(function (a, b) {
    var firstGroupId = a.groupId;
    var secondGroupId = b.groupId;

    return (firstGroupId === secondGroupId) ? a.value > b.value : firstGroupId > secondGroupId;
});

答案 2 :(得分:1)

复制我的recent answer

cmp = function(a, b) {
    if (a > b) return +1;
    if (a < b) return -1;
    return 0;
}

array.sort(function(a, b) { 
    return cmp(a.groupId,b.groupId) || cmp(a.value,b.value)
})

答案 3 :(得分:0)

Javascript多标准排序

如果您想按 groupId value 排序,可以使用我在下面粘贴的排序功能(JsFiddle:http://jsfiddle.net/oahxg4u3/6/) 。此排序功能也可用于按n值或单个值排序。

定义:

function sortByCriteria(data, criteria) {
    return data.sort(function (a, b) {

        var i, iLen, aChain, bChain;

        i = 0;
        iLen = criteria.length;
        for (i; i < iLen; i++) {        
            aChain += a[criteria[i]];
            bChain += b[criteria[i]];
        }

        return aChain.localeCompare(bChain);
    });
}

调用:

var data = [
    {value:"fruit", desc:"fruit", groupId:2, userId:4},
    {value:"aGan", desc:"normal user", groupId:4, userId:5},
    {value:"father's home ", desc:"normal user", groupId:2, userId:4}
];
var criteria = ["groupId", "value"];

sortByCriteria(data, criteria);