Multi-sorting a multi-dimensional array

前端 未结 4 454
礼貌的吻别
礼貌的吻别 2020-12-20 23:01
var availableTags = [
    {value:\"fruit\",desc:\"fruit\",groupId:2,userId:4},
    {value:\"aGan\",desc:\"normal user\",groupId:4,userId:5},
    {value:\"father\'s h         


        
相关标签:
4条回答
  • 2020-12-20 23:23

    How about

    .sort(function (a, b) {
        var firstGroupId = a.groupId;
        var secondGroupId = b.groupId;
    
        return (firstGroupId === secondGroupId) ? a.value > b.value : firstGroupId > secondGroupId;
    });
    
    0 讨论(0)
  • 2020-12-20 23:28

    Change the return statement to

    return a.groupId > b.groupId || (a.groupId == b.groupId && a.value > b.value);
    
    0 讨论(0)
  • 2020-12-20 23:38

    Copying my 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)
    })
    
    0 讨论(0)
  • 2020-12-20 23:38

    Javascript Multi-Criteria Sort

    If you want to sort by groupId and value, you can use the sort function that I've pasted below (JsFiddle: http://jsfiddle.net/oahxg4u3/6/). This sort function can also be used to sort by n-values, or by a single value.

    Define:

    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);
        });
    }
    

    Invoke:

    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);
    
    0 讨论(0)
提交回复
热议问题