【发布时间】:2020-01-28 09:01:00
【问题描述】:
我有以下数组:
const items = [
{ name: 'john', class: 'one', section: 'a' },
{ name: 'john2', class: 'one', section: 'b' },
{ name: 'john3', class: 'one', section: 'a' },
{ name: 'john4', class: 'two', section: 'a' },
{ name: 'john5', class: 'two', section: 'b' },
{ name: 'john6', class: 'two', section: 'b' },
{ name: 'john7', class: 'three', section: 'a' },
{ name: 'john8', class: 'four', section: 'a' },
{ name: 'john9', class: 'four', section: 'b' }
];
我希望它以这种方式分组:
[
{
'oneA': [
{ name: 'john', class: 'one', section: 'a' },
{ name: 'john3', class: 'one', section: 'a' }
]
},
{
'oneB': [
{ name: 'john2', class: 'one', section: 'b' }
]
},
{
'twoA': [
{ name: 'john4', class: 'two', section: 'a' }
]
},
{
'twoB': [
{ name: 'john5', class: 'two', section: 'b' },
{ name: 'john6', class: 'two', section: 'b' }
]
},
{
'threeA': [
{ name: 'john7', class: 'three', section: 'a' }
]
},
{
'fourA': [
{ name: 'john8', class: 'four', section: 'a' }
]
},
{
'fourB': [
{ name: 'john9', class: 'four', section: 'b' }
]
}
]
我尝试过这样的事情:
items.sort(function (a, b) {
if (a.class > b.class) return 1;
if (a.class < b.class) return -1;
if (a.section > b.section) return 1;
if (a.section < b.section) return -1;
})
这可以按我的意愿对数组进行排序,但它没有像我上面描述的那样分组。 你知道达到那个目的的方法吗?
【问题讨论】:
-
为什么你的结果需要包含一个对象数组,每个对象都有一个键?为什么不只是一个具有多个键的对象?排序逻辑是什么?您是否尝试根据数字的文本表示进行排序?
-
@RobbyCornelissen 我需要一个对象数组,因为我会在它上面循环,然后我会在每个数组中循环。
-
你确定下面的节点也有“三”类值吗? ``` { 'fourA': [ { name: 'john7', class: 'three', section: 'a' }, { name: 'john8', class: 'four', section: 'a' } ] } ```
标签: javascript arrays sorting object grouping