javascript - 使用对象过滤对象数组驻留在嵌套数组属性中
问题描述
我有以下用例,
我有,
- 一个对象数组,其中包含一个列表
courses
- 包含
students
嵌套对象的数组array: studies
我需要找到任何学生都没有学习过的课程。
如何做到这一点?
下面是代码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' }];
解决方案
您可以将id
已经学习过的课程保存students
到aSet
中,以便我们以后可以检查该课程是否已经学习过。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);
推荐阅读
- vuejs2 - Vue.js - 父 <-> 插槽通信
- ios - Swift UnsafeMutableRawPointer 错误
- php - PHP查找并替换由管道符号分隔的输入文本给出的多个单词
- javascript - CleanWebpackPlugin 不让我重建
- sqlite - 尝试访问pyQt中的数据库时未加载驱动程序
- android - values-swXXXdp 和 values-swXXXdp-(ldpi、mdpi、hdpi 或 xhpdi)之间的区别?
- xml - XSL 选择第 N 个字段
- java - Map.contains 与 Map.values().stream().filter.find
- laravel - Symfony \ Component \ Debug \ Exception \ FatalThrowableError(E_ERROR)类'App \ Providers \ View'未找到
- c# - $Expand 使用实体框架在 Webapi 可查询端点上失败