javascript - 如何对数组进行排序取决于Javascript中的相同值
问题描述
例如,我有一个如下所示的数组。
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)
推荐阅读
- encryption - 无法在 Ubuntu 18.04 上使用 gpg 签署文件
- flutter - 我是否需要在 Dart 中处理 mobx 的 `autorun` 实例以及如何处理?
- spring - 过滤过滤的数据
- java - 无法使用 AWS CodeDeploy 部署 Springboot 应用程序 AWS Ubuntu 实例
- java - 如何在 JPanel 中使用文件选择器
- javascript - 节点js会话销毁不重定向
- javascript - 防止像figma那样放大网页,
- rxjs - 延迟后重新执行异步 RxJS 流
- php - 如何在 DOM 元素回显中设置 img 类?
- django - 按组名选择的 DRF 过滤器