javascript - 在 javascript 对象数组中分组和排序

标签 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 上进行重组,并在 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);
  }
}

然后您可以使用排序函数,首先根据项目的 GroupgroupOrder 中的索引进行排序,然后,如果它们具有相同的组,则只需排序级别:

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/

相关文章:

javascript - Angular 2 Child Routing (v3) 'Cannot read property ' 注释' of undefined'

javascript - 下拉列表更改事件在 IE9 中不起作用

javascript - 在 Jquery 中为盒子制作动画

javascript - 如何更快、更智能地突出显示单词/术语?

javascript - 如何在 Wix 网站上运行 jquery?

arrays - 链表、数组和硬件内存缓存

javascript - 从 iFrame 内部加载的外部页面访问 IFrame 元素

javascript - 如何在 TestComplete 中使用 QuerySelector 方法

php - 将 PHP 数组排序为列

C# 数组还是字典?