我有以下用例,
我有,
- 包含
类(class)
列表的对象数组 - 包含
students
的对象数组以及嵌套的array: studies
我需要找到没有任何学生学习过的类(class)。
如何实现?
下面是代码sinnpient。
let courses = [
{ id: 'A' },
{ id: 'B' },
{ id: 'C' },
{ id: 'D' }, <-- not studied by any one
{ id: 'E' },
{ id: 'F' }, <-- not studied by any one
];
let students = [
{
name: 'STD1',
study: [
{ id: 'A' },
{ id: 'C' }
]
},
{
name: 'STD2',
study: [
{ id: 'B' },
{ id: 'E' }
]
}
];
预期输出
const notUsedCourse = [{ id: 'D' }, { id: 'F' }];
最佳答案
您可以将学生
学习过的类(class)id
保存到一个Set
中,这样我们就可以检查一门类(class)是否已经学习过之后。
filter
和 some
组合的解决方案的优势在于,当 courses
和 students
变得更大,因为前者的时间复杂度为 O(n^3)
。
const courses = [
{ id: 'A' },
{ id: 'B' },
{ id: 'C' },
{ id: 'D' },
{ id: 'E' },
{ id: 'F' },
];
const students = [
{
name: 'STD1',
study: [
{ id: 'A' },
{ id: 'C' }
]
},
{
name: 'STD2',
study: [
{ id: 'B' },
{ id: 'E' }
]
}
];
const usedCourseIds = new Set(students.flatMap(student => student.study).map(course => course.id));
const notUsedCourses = courses.filter(course => !usedCourseIds.has(course.id));
console.log(notUsedCourses);
关于javascript - 使用嵌套数组属性中的对象过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58501144/