javascript - 使用嵌套数组属性中的对象过滤对象数组

标签 javascript arrays typescript

我有以下用例,

我有,

  • 包含类(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)是否已经学习过之后。 filtersome 组合的解决方案的优势在于,当 coursesstudents 变得更大,因为前者的时间复杂度为 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/

相关文章:

javascript - 使用 jQuery 拆分包含 TextNode 和元素的元素

javascript - 由于使用 'addEventListener' 导入的脚本, enzyme 无法浅渲染

javascript - React-Native 渲染多个图像

java - 检查数组中的特定整数

arrays - 如何在 Swift 中合并两个排序数组?

typescript - 从外部访问私有(private)属性(property)

javascript - Chrome扩展通知窗口调试工具

javascript - 如何分割字符串并重复字符?

javascript - Angular 警告 : sanitizing HTML stripped some content?

c# - 使用内置 PDF 阅读器的 chrome 的 TypeScript