我进行了搜索,但找不到 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"}
]
我需要能够按照它们首次出现的顺序保持组,所以我需要,在这种情况下,保持红色、绿色、蓝色然后黄色的组顺序,但在这些组内排序
最佳答案
首先,您需要遍历数组一次以设置一个包含组顺序的数组,因为要维护该顺序:
// 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
中的索引进行排序,然后,如果它们具有相同的组,则只需排序级别
:
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;
}
});
关于javascript - 在 javascript 对象数组中分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23451023/