javascript - 在javascript中按多个对象属性对数组进行排序
问题描述
var array = [
{
"checked": true,
"name":"Name",
"type": {
"id": 1,
"tag": "tag"
}
},
{
"checked": true,
"name":"Name",
"type": {
"id": 3,
"tag": "tag"
}
},
{
"checked": false,
"name":"Name",
"type": {
"id": 2,
"tag": "tag"
}
},
];
我想通过检查和 type.id 对数组进行排序。我使用以下排序代码,但“type.id”似乎有问题,因为如果选中,我的列表没有按那些分组。
sortByPriority(array, ['checked', 'type.id']);
sortByPriority(data, priorities) {
if (priorities.length == 0 || data.length == 0) {
return data;
}
const nextPriority = priorities[0];
const remainingPriorities = priorities.slice(1);
const matched = data.filter(item => item.hasOwnProperty(nextPriority));
const remainingData = data.filter(item => !item.hasOwnProperty(nextPriority));
return this.sortByPriority(matched, remainingPriorities)
.sort((a, b) => (a[nextPriority] > b[nextPriority]) ? 1 : -1)
.concat(this.sortByPriority(remainingData, remainingPriorities));
}
关于如何对类型对象进行排序的任何想法?
(我无法找到另一个问题,其答案是通用排序器能够根据数组中的对象进行排序)
解决方案
您可以对嵌套属性使用嵌套方法,并采用一组函数来比较值。
function sortByPriority(array, keys, fn) {
function getValue(o, k) {
return k.split('.').reduce((p, l) => (p || {})[l], o);
}
return array.sort((a, b) => {
var d;
keys.some((k, i) => d = fn[i](getValue(a, k), getValue(b, k)));
return d;
});
}
var array = [{ checked: false, name: "Name", type: { id: 2, tag: "tag" } }, { checked: true, name: "Name", type: { id: 3, tag: "tag" } }, { checked: true, name: "Name", type: { id: 1, tag: "tag" } }];
sortByPriority(array, ['checked', 'type.id'], [(a, b) => b - a, (a, b) => a - b]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- r - 删除导致 R 中某个值的行
- if-statement - Java Beginner:nextLine 问题,while 和 if 循环错误
- c# - 如何仅在应用程序关闭时才结束前台服务
- python - 用于在脚本中修复 std I/O 重定向问题以添加 GUI 的 Python 想法
- flutter - 如何在顶部和左侧边距领先的图标颤动
- apache-kafka-streams - 外键在流式数据库更新上加入两个 ktable
- android - 改造后多部分原始数据
- javascript - 使用 vue js 和 axios 下载时 XLSX 文件损坏
- python-3.x - 无法在python3中将列表转换为字典
- java - Android中的动画启动画面,没有制作启动活动