首页 > 解决方案 > 使用对象过滤对象数组驻留在嵌套数组属性中

问题描述

我有以下用例,

我有,

我需要找到任何学生都没有学习过的课程。

如何做到这一点?

下面是代码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' }];

标签: javascriptarraystypescript

解决方案


您可以将id已经学习过的课程保存students到aSet中,以便我们以后可以检查该课程是否已经学习过。filter与和组合的解决方案的优势在于,当和some的大小变大时,该解决方案将快得多,因为前者的时间复杂度为。coursesstudentsO(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);


推荐阅读