【发布时间】:2019-10-04 23:29:24
【问题描述】:
我有一个对象数组,它在另一个 obj 数组中,如何根据内部数组中的相等 actionId 键对该数组进行排序?
这是我原来的数组:
const arrayOfItems = {
items: [
{
item: '1',
anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
},
{
item: '2',
anotherArray: []
},
{
item: '3',
anotherArray: []
},
{
item: '4',
anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
},
{
item: '5',
anotherArray: []
},
{
item: '6',
anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
}
]
};
结果应该是所有具有相同 actionId 在彼此下的项目
sortedArray = {
items: [
{
item: '1',
anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
},
{
item: '4',
anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
},
{
item: '6',
anotherArray: [{ actionId: '1234-dh4t-tr21-6sw8' }]
},
...
]
};
这是我尝试过的:
const sortingArray = arrayOfItems.items.sort((a, b) => {
return a.anotherArray > 0 && a.anotherArray[0].actionId.localeCompare(b.anotherArray[0].actionId);
})
【问题讨论】:
-
发布的问题似乎根本不包括任何解决问题的尝试。 Stack Overflow 期待您 try to solve your own problem first,因为您的尝试有助于我们更好地了解您想要什么。请编辑问题以显示您尝试过的内容,以说明您在minimal reproducible example 中遇到的特定障碍。欲了解更多信息,请参阅How to Ask 并拨打tour。
-
网络上有无数的教程正是针对这种情况,只需快速搜索即可帮助您完成作业。干杯。
-
@ChrisW。我找了但是没找到,能不能给我写个网址
-
a.discounts > 0应该是a.discounts.length > 0。 -
我认为你不能用
sort()做到这一点。比较函数只能指定元素的相对顺序,不能强制组合在一起。
标签: javascript