javascript - 是否可以通过另一个对象的属性对对象数组进行排序?
问题描述
所以我有一个看起来像这样的对象数组:
group: [
0: {id: "16", name: "P1", courseId: "6", mentorId: "1", chatUrl: false, students: {0: 1, 1: 10, 2: 11},…}
1: {id: "17", name: "C1", courseId: "7", mentorId: "3", chatUrl: false, students: {0: 15, 1: 16, 2: 18},…}
2: {id: "22", name: "P2", courseId: "6", mentorId: "1", chatUrl: false, students: {0: 12, 1: 13, 2: 9},…}
3: {id: "23", name: "C2", courseId: "7", mentorId: "3", chatUrl: false, students: {0: 17, 1: 19, 2: 20},…}
4: {id: "24", name: "DEV", courseId: "10", mentorId: "1", chatUrl: false,…}].
我正在尝试按导师姓名对其进行排序,导师姓名是另一个数组中对象的属性,如下所示:
mentor: [
0: {id: "0", firstName: "Daniel", about: false,…}
1: {id: "1", firstName: "Mark", aboutl:false,…}
2: {id: "3", firstName: "Eric", about: false,…}
3: {id: "6", firstName: "John", about: false,…} ]
这些组通过属性mentorId与导师相关,因此我必须将组数组中的属性mentorId与导师数组中的id进行比较,以获取组的所有导师,然后按这些导师的名字对组进行排序。这甚至可能吗?
输出应显示按导师名字字母顺序排序的所有组,如下所示:
group: [
0: {id: "23", name: "C2", courseId: "7", mentorId: "3", chatUrl: false, students: {0: 17, 1: 19, 2: 20},…}
1: {id: "17", name: "C1", courseId: "7", mentorId: "3", chatUrl: false, students: {0: 15, 1: 16, 2: 18},…}
2: {id: "22", name: "P2", courseId: "6", mentorId: "1", chatUrl: false, students: {0: 12, 1: 13, 2: 9},…}
3: {id: "16", name: "P1", courseId: "6", mentorId: "1", chatUrl: false, students: {0: 1, 1: 10, 2: 11},…}
4: {id: "24", name: "DEV", courseId: "10", mentorId: "1", chatUrl: false,…}
]
解决方案
您可以首先按 firstName 属性对导师数组进行排序,然后创建一个对象,其中键是 id,值是该对象在排序数组中的索引。然后,您可以sort
在组数组上使用方法并按mentorId
顺序对象中的属性值进行排序。
const groups = [{"id":"16","name":"P1","courseId":"6","mentorId":"1","chatUrl":false,"students":{"0":1,"1":10,"2":11}},{"id":"17","name":"C1","courseId":"7","mentorId":"3","chatUrl":false,"students":{"0":15,"1":16,"2":18}},{"id":"22","name":"P2","courseId":"6","mentorId":"1","chatUrl":false,"students":{"0":12,"1":13,"2":9}},{"id":"23","name":"C2","courseId":"7","mentorId":"3","chatUrl":false,"students":{"0":17,"1":19,"2":20}},{"id":"24","name":"DEV","courseId":"10","mentorId":"1","chatUrl":false}]
const mentors = [{"id":"0","firstName":"Daniel","about":false},{"id":"1","firstName":"Mark","aboutl":false},{"id":"3","firstName":"Eric","about":false},{"id":"6","firstName":"John","about":false}]
mentors.sort((a, b) => a.firstName.localeCompare(b.firstName))
const order = mentors.reduce((r, { id }, i) => (r[id] = i, r), {})
groups.sort((a, b) => order[a.mentorId] - order[b.mentorId])
console.log(groups)
推荐阅读
- spring - 如何在 Kotlin 中构建 XMLRPC 客户端,使用 Gradle 管理依赖关系?
- javascript - Javascript - 将页面保存到本地存储
- html - css circle 在自定义无线电控制器中看起来很乱
- php - 在 Laravel 中创建具有嵌套类别的选择选项按钮
- keras - ImageData Generator 中的 validation_split 返回 0 张图像
- r - 从 R 问题中调用 Julia
- python - 将 n 个值插入一个空的双向链表(伪代码)
- node.js - 从我的 rest api 中提取数据到我的 VueJS 组件的数组数据属性中
- python - Python Facebook API v3.1
- python - Django:唯一的 order_reference