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

时间:2014-05-03 23:48:33

标签: javascript jquery arrays sorting grouping

我搜索过但我找不到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上进行重新组织,并在Level上对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"}
  ]

我需要能够按照他们第一次出现的顺序保持小组,所以我需要,在这种情况下,保持红色,绿色,蓝色然后是黄色的组顺序,但在这些组中排序

1 个答案:

答案 0 :(得分:3)

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

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

然后你可以使用排序函数,首先按照Group中项目的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;
  }
});