如何解决是否可以通过另一个对象的属性对对象数组进行排序?
所以我有一个看起来像这样的对象数组:
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",students: {0: 15,1: 16,2: 18},…}
2: {id: "22",name: "P2",students: {0: 12,1: 13,2: 9},…}
3: {id: "23",name: "C2",students: {0: 17,1: 19,2: 20},…}
4: {id: "24",name: "DEV",courseId: "10",…}].
我正在尝试按指导者名称对其进行排序,指导者名称是另一个数组中对象的属性,如下所示:
mentor: [
0: {id: "0",firstName: "Daniel",about: false,…}
1: {id: "1",firstName: "Mark",aboutl:false,…}
2: {id: "3",firstName: "Eric",…}
3: {id: "6",firstName: "John",…} ]
组通过属性mentorId与指导者相关,因此我必须比较组数组中的属性mentorId与指导者数组中的ID,以获取组的所有指导者,然后按这些指导者firstName对组进行排序。这有可能吗?
输出应显示按指导者名字的字母顺序排列的所有组,如下所示:
group: [
0: {id: "23",…}
1: {id: "17",…}
2: {id: "22",…}
3: {id: "16",…}
4: {id: "24",…}
]
解决方法
您可以先按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","students":{"0":15,"1":16,"2":18}},{"id":"22","name":"P2","students":{"0":12,"1":13,"2":9}},{"id":"23","name":"C2","students":{"0":17,"1":19,"2":20}},{"id":"24","name":"DEV","courseId":"10","chatUrl":false}]
const mentors = [{"id":"0","firstName":"Daniel","about":false},{"id":"1","firstName":"Mark","aboutl":false},{"id":"3","firstName":"Eric",{"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)
,
var group= [
{id: "17",name: "C1",courseId: "7",mentorId: "3",chatUrl: false,students: {0: 15,1: 16,2: 18}},{id: "16",name: "P1",courseId: "6",mentorId: "1",students: {0: 1,1: 10,2: 11}},{id: "22",name: "P2",students: {0: 12,1: 13,2: 9}},{id: "23",name: "C2",students: {0: 17,1: 19,2: 20}},{id: "24",name: "DEV",courseId: "10",chatUrl: false}]
var mentor=[
{id: "0",firstName: "Daniel",about: false},{id: "1",firstName: "Mark",aboutl:false},{id: "3",firstName: "Eric",{id: "6",firstName: "John",about: false}
]
group = group.sort( (a,b) => {
for(i=0;i<mentor.length;i++){
if (a.mentorId===mentor[i].id){a.mentorName=mentor[i].firstName}
if (b.mentorId===mentor[i].id){b.mentorName=mentor[i].firstName}
}
if(a.mentorName<b.mentorName){return -1}
else if(a.mentorName==b.mentorName){return 0}
else{return 1}
});
console.log(group);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。