Search code examples
javascriptarraysjavascript-objects

Map value of an attribute in one object array to an attribute in another object array Javascript


I have two arrays of objects:

courses = [ { _id: 999, courseCode: "Eng1" },
{ _id: 777, courseCode: "Sci1" },
{ _id: 666, courseCode: "Eng2" },
{ _id: 888, courseCode: "Sci2" }  ]

sectionCourses = [ { sectionCode: "1A", courseId: "999" },
{ sectionCode: "1A", courseId: "777" },
{ sectionCode: "2A", courseId: "666" }, 
{ sectionCode: "2A", courseId: "888" }  ]

I want to filter the courses array in such a way that it contains only the courses that are not in a section. For example if I select section with sectionCode: "2A", the courses array should only contain

courses = [ { _id: 999, courseCode: "Eng1" },
    { _id: 777, courseCode: "Sci1" },
    { _id: 888, courseCode: "Sci2" }  ]

I tried to do this way:

 courses = courses.filter(c => !(sectionCourses.includes(c._id)))

but I know this is incomplete because I can't figure out how to access courseId in sectionCourses.

Please help.


Solution

  • You can't use .includes() method to find the whole object by its _id, includes compares the whole objects and doesn't search for a specific property.

    What you can do here is to get an array of courseIds to be ignored based on the sectionCode you provided, and then filter the courses that their _id doesn't exist in this array of ids:

    function getCourses(catCode) {
    
      var coursesIdstoIgnore = sectionCourses.filter(s => s.sectionCode === catCode).map(s => s.courseId);
      return courses.filter(c => coursesIdstoIgnore.indexOf(c["_id"].toString()) == -1);
    }
    

    Demo:

    var courses = [{
        _id: 999,
        courseCode: "Eng1"
      },
      {
        _id: 777,
        courseCode: "Sci1"
      },
      {
        _id: 666,
        courseCode: "Eng2"
      },
      {
        _id: 888,
        courseCode: "Sci2"
      }
    ];
    
    var sectionCourses = [{
        sectionCode: "1A",
        courseId: "999"
      },
      {
        sectionCode: "1A",
        courseId: "777"
      },
      {
        sectionCode: "2A",
        courseId: "666"
      },
      {
        sectionCode: "2A",
        courseId: "888"
      }
    ];
    
    function getCourses(catCode) {
      var cousesIdstoIgnore = sectionCourses.filter(s => s.sectionCode === catCode).map(s => s.courseId);
      console.log(cousesIdstoIgnore);
    
      return courses.filter(c => cousesIdstoIgnore.indexOf(c["_id"].toString()) == -1);
    
    }
    
    var results = getCourses("2A");
    
    
    console.log(results);