此问题已经在这里有了答案:
例如,我有一个类似下面的数组。
const array = [
{name: 'apple', type: 'fruit' },
{name: 'computer', type: 'machine' },
{name: 'cherry', type: 'fruit' },
{name: 'pear', type: 'fruit' },
{name: 'galaxy', type: 'machine' },
{name: 'KIA', type: 'car' },
]
排序后,
const sortedArray = {
fruit: [
{name: 'apple', type: 'fruit' },
{name: 'cherry', type: 'fruit' },
{name: 'pear', type: 'fruit' }
],
car: [
{name: 'KIA', type: 'car' }
],
machine: [
{name: 'computer', type: 'machine'},
{name: 'galaxy', type: 'machine'}
]
}
所以我尝试如下所示
var sortedArray={}
for(let i=0; i< array.length; i++){
this.sortedBags[this.bags[i].intent] = [];
}
而且我必须按每个键。但是我不知道该怎么做。您能推荐一些更有效的代码吗?非常感谢您阅读。
您首先需要对值进行排序,然后才需要对每个组进行排序