【问题标题】:Group and sort within an array of javascript objects在 javascript 对象数组中进行分组和排序
【发布时间】:2014-06-20 11:43:45
【问题描述】:

我已经搜索过,但找不到 JavaScript/jQuery 解决方案。 我有一个这样的对象数组

  MLDS = [ 
    {"Group": "Red","Level": "Level 2"},
    {"Group": "Green","Level": "Level 1"},
    {"Group": "Red","Level": "Level 1"},
    {"Group": "Blue","Level": "Level 1"},
    {"Group": "Green","Level": "Level 2"},
    {"Group": "Yellow","Level": "Level 1"}
  ]

我希望能够在 Group 上进行重组,并在 Group 内对 Level 进行排序,以按新顺序返回另一个对象数组,所以

  MLDS = [ 
    {"Group": "Red","Level": "Level 1"},
    {"Group": "Red","Level": "Level 2"},
    {"Group": "Green","Level": "Level 1"},
    {"Group": "Green","Level": "Level 2"},
    {"Group": "Blue","Level": "Level 1"},
    {"Group": "Yellow","Level": "Level 1"}
  ]

我需要能够将组保持在它们首次出现的顺序中,所以我需要在这种情况下保持红色、绿色、蓝色然后黄色的组顺序,但在这些组中排序

【问题讨论】:

    标签: javascript jquery arrays sorting grouping


    【解决方案1】:

    首先,您需要遍历数组一次以设置一个包含组顺序的数组,因为这是要维护的:

    // this will hold the unique groups that have been found
    var groupOrder = [];
    
    // iterate through the array,
    // when a new group is found, add it to the groupOrder
    for (var i = 0; i < MLDS.length; i++) {
      // this checks that the current item's group is not yet in groupOrder
      // since an index of -1 means 'not found'
      if (groupOrder.indexOf(MLDS[i].Group) === -1) {
        // add this group to groupOrder
        groupOrder.push(MLDS[i].Group);
      }
    }
    

    然后您可以使用排序功能,首先按项目的GroupgroupOrder 中的索引进行排序,然后,如果它们具有相同的组,则只需按Level 排序:

    MLDS.sort(function(a, b) {
      if (groupOrder.indexOf(a.Group) < groupOrder.indexOf(b.Group)) {
        return -1;
      } else if (groupOrder.indexOf(a.Group) > groupOrder.indexOf(b.Group)) {
        return 1;
      } else if (a.Level < b.Level) {
        return -1;
      } else if (a.Level > b.Level) {
        return 1;
      } else {
        return 0;
      }
    });
    

    【讨论】:

    • 完美。正是我想要的
    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2021-03-30
    • 1970-01-01
    • 2012-05-02
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多