首页 > 解决方案 > 是否可以通过另一个对象的属性对对象数组进行排序?

问题描述

所以我有一个看起来像这样的对象数组:

    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,…}
]

标签: javascriptarrayssortingobject

解决方案


您可以首先按 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)


推荐阅读