简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM