How to check if a sub-array contains all elements of another array javascript

I have an array of projects called rawProjects which looks like this:

rawProjects = [
    {
         id: 1,
         name: "proj1",
         technology: [
             0: {id: 21, project_id: 1,name: "java"},
             1: {id: 22, project_id: 1,name: "c++"}
          ]
    },
    {
         id: 2,
         name: "proj2",
         technology: [
             0: {id: 23, project_id: 2,name: "sql"},
             1: {id: 24, project_id: 2,name: "python"},
             2: {id: 25, project_id: 2,name: "react"}

         ]
    }
]

I also have an array of technology called tempTags which contains the technologies that the user enters to search from. So far I have been able to do the OR case where in I return the projects which contain either of the technologies mentioned by the user using:

const filteredProjects = rawProjects.filter(x => x.technology.some(g => tempArr.includes(g.name)))

So for example if tempTags = [sql, c++] both projects will be returned.

How do I implement the AND case such that only projects that contain both of these technologies are returned. Eg if tempTags = [java, c++] , only the first project will be returned. If tempTags = [sql, c++], nothing will be returned?

20 thoughts on “How to check if a sub-array contains all elements of another array javascript”

  1. Iterate over the tempTags and check that .every one of them is included:

    const rawProjects = [
        {
             id: 1,
             name: "proj1",
             technology: [
                 {id: 21, project_id: 1,name: "java"},
                 {id: 22, project_id: 1,name: "c++"}
              ]
        },
        {
             id: 2,
             name: "proj2",
             technology: [
                 {id: 23, project_id: 2,name: "sql"},
                 {id: 24, project_id: 2,name: "python"},
                 {id: 25, project_id: 2,name: "react"}
    
             ]
        }
    ]
    
    const tempTags = ['java', 'c++'];
    const filtered = rawProjects.filter(
      p => {
        const techNames = p.technology.map(({ name }) => name);
        return tempTags.every(
          tag => techNames.includes(tag)
        );
      }
    );
    console.log(filtered);

    You’ll also need to fix your syntax: arrays do not have key-value pairs, only values. (Remove the 0:, 1:, etc), and make sure to put commas in between array values (there should be a comma after "python"})

    Reply

Leave a Comment