How to filter an array based on another array?

I have been struggling with this easy change. I basically have two arrays:

let apps = [{name: "Insights", id: "INS"}, {name: "Recruit", id: "REC"}];

let securityApps = ["bw", "INS"];

I am basically trying to filter down apps based on the elements inside securityApps

The result I am wanting to achieve is: [{name: "Insights", id: "INS"}]; (since INS is what they have in common in terms of ID) but still pass in apps variable

Here is what I have started:

apps.filter((app) => {
        securityApps.forEach((sgApp) => {
          if (app.id === sgApp){
            return app;
          }
        })
      });

apps is later implemented as

apps.map(...

Answer

You can do it this way, using filter and indexOf or includes:

let apps = [{
  name: "Insights",
  id: "INS"
}, {
  name: "Recruit",
  id: "REC"
}];

let securityApps = ["bw", "INS"];

const filtered = apps.filter(app => securityApps.indexOf(app.id) > -1)

console.log(filtered)

const filtered2 = apps.filter(app => securityApps.includes(app.id))

console.log(filtered2)

Using indexOf would be better as includes won’t work in Internet Explorer without polyfills. And perhaps indexOf is faster on chrome as per this post.