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(...

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

it's ok no problem
@ZiaurRehman I think using includes is cleaner and shorter. And Internet Explorer usage share is extremely low. And which one is faster will keep changing and nobody cares. includes is short and clean as your answer suggests. +1
Thank you @AjeetShah!
2

Really simple answer

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.