0

how do i filter an array from the given values of another array? The newCampaignId varable is the one i want to filter through. I do it like so:

const newCampaignId = ["101","102","103","104"] // not used
const newCampaign = subscriptions.filter((sub) => sub.id == "101" || sub.id == "102" || sub.id =="103" || sub.id == "104");

But i am sure there is an easier way of doing this. Any ideas?

  • 1
    You can return `newCampaignId.includes(sub.id)` which will return true when the subscription id is in your array (see above link). – Nick Parsons Jan 06 '22 at 10:36

1 Answers1

1

You can use Array.includes property. You can read more about it on https://www.w3schools.com/jsref/jsref_includes_array.asp

const newCampaign = subscriptions.filter(sub => newCampaignId.includes(sub.id));
Sahil Rajpal
  • 510
  • 4
  • 8
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. – Luca Kiebel Jan 06 '22 at 10:41
  • I just added the explanation and resource for more knowledge. – Sahil Rajpal Jan 06 '22 at 10:44
  • i have used the code snippet you provided but it gives me an empty array. Subscriptions is a array of dictionaries that is located in another folder. –  Jan 06 '22 at 10:59
  • So what i am trying to do is to make a new array which is filtered by the newCampaginId of the subscription dictionary. thanks for answering btw –  Jan 06 '22 at 11:00
  • I also had the impression that includes returns true or false –  Jan 06 '22 at 11:02
  • can you post the subscription array. for me to check – Sahil Rajpal Jan 06 '22 at 11:03