简体   繁体   English

在javascript对象数组中进行分组和排序

[英]Group and sort within an array of javascript objects

I have searched but I can't quite find a JavaScript/jQuery solution. 我搜索过但我找不到JavaScript / jQuery解决方案。 I have an array of objects like this 我有一个像这样的对象数组

  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"}
  ]

I want to be able to reorganize on Group and within the Group sort on Level to return another array of the objects in that new order so 我希望能够在Group上进行重新组织,并在Group上进行排序,以返回该新订单中的另一个对象数组,以便

  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"}
  ]

I need to be able to keep the Group in the order in which they first appear so I need, in this case to maintain the group order of Red, Green, Blue then yellow, but sort within those groups 我需要能够按照他们第一次出现的顺序保持组,所以我需要,在这种情况下,保持组,红色,绿色,蓝色然后是黄色,但在这些组中排序

First you need to iterate through the array once to set up an array that will contain the order of the groups, since that is to be maintained: 首先,您需要遍历数组一次以设置一个包含组顺序的数组,因为要维护它:

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

Then you can use a sorting function that first sorts by what index the item's Group has in the groupOrder and then, if they have the same group, simply sorts by Level : 然后,您可以使用排序函数,该函数首先按项目GroupgroupOrder中的groupOrder ,然后,如果它们具有相同的组,则只按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;
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM