【问题标题】:Multi-sorting a multi-dimensional array对多维数组进行多排序
【发布时间】:2012-02-21 08:49:51
【问题描述】:
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 排序?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

将return语句改为

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

【讨论】:

  • 最好在.sort()函数回调中返回-1,0,1。
  • 感谢您告诉我。
【解决方案2】:

怎么样

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

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

【讨论】:

    【解决方案3】:

    复制我的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)
    })
    

    【讨论】:

      【解决方案4】:

      Javascript 多条件排序

      如果你想按 groupIdvalue 排序,可以使用我在下面粘贴的排序函数(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);
      

      【讨论】:

        猜你喜欢
        • 2010-10-13
        • 2012-06-10
        • 2011-03-15
        • 2011-10-23
        • 2014-02-25
        相关资源
        最近更新 更多