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.
CodePudding user response:
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)