1

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(...
BluePilot
  • 373
  • 3
  • 15

2 Answers2

3

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.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
2

Really simple answer

const newArray = apps.filter(app => securityApps.includes(app.id)))
Zia ur Rehman
  • 573
  • 3
  • 15