例如,我有一个如下所示的数组。
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] = [];
}
我必须按下每个键。但我不知道该怎么做。
您能推荐一些更有效的代码吗?
非常感谢您阅读它。
最佳答案
您首先需要对值进行排序,然后需要对每个组进行排序
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'}]
let sorted = array.reduce((op, inp) => {
let type = inp.type;
op[type] = op[type] || [];
op[type].push(inp);
return op
}, {})
for (let key in sorted) {
let value = sorted[key];
sorted[key] = value.sort((a, b) => a.name.localeCompare(b.name));
}
console.log(sorted)
关于javascript - 如何根据 Javascript 中的相同值对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58677369/