如何对数组进行排序取决于Javascript中的相同值[duplicate]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

例如,我有一个类似下面的数组。

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] = [];
}

而且我必须按每个键。但是我不知道该怎么做。您能推荐一些更有效的代码吗?非常感谢您阅读。

javascript
1个回答
0
投票

您首先需要对值进行排序,然后才需要对每个组进行排序

© www.soinside.com 2019 - 2024. All rights reserved.