Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering array based on another array

I am trying to filter arr1, with respect to arr2
what I am trying to achieve is, get all objects of arr1 where it’s corresponding "genre" property in arr2 is "true"

const arr1=[
  {
    "id":1,"genre":["horror","drama","mystery"]
  },
   {
    "id":2,"genre":["romance"]
  },
   {
    "id":3,"genre":["adventure","drama"]
  },
]

const arr2=[
  {
    "genre":"horror",
    "checked":false
  },
  {
    "genre":"drama",
    "checked":true
  },
  {
    "genre":"mystery",
    "checked":false
  },
  {
    "genre":"romance",
    "checked":false
  },
  {
    "genre":"adventure",
    "checked":true
  }
]

so the desired output would be:

[
 {
   "id":1,"genre":["horror","drama","mystery"]
  },
{
    "id":3,"genre":["adventure","drama"]
  },
]

I have tried some configurations the javascript filter methods but i just can’t think of something that works as described. Any help would be appreciated.
Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This should work.

Use .filter on first array and .some on the other array to determine if it is checked and element of first array contains target genre using .indexOf or even better .includes

const arr1=[
  {
    "id":1,"genre":["horror","drama","mystery"]
  },
   {
    "id":2,"genre":["romance"]
  },
   {
    "id":3,"genre":["adventure","drama"]
  },
]

const arr2=[
  {
    "genre":"horror",
    "checked":false
  },
  {
    "genre":"drama",
    "checked":true
  },
  {
    "genre":"mystery",
    "checked":false
  },
  {
    "genre":"romance",
    "checked":false
  },
  {
    "genre":"adventure",
    "checked":true
  }
]

const result = arr1.filter(a1 => arr2.some(a2 => a2.checked && a1.genre.includes(a2.genre)))
console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading