0
let array1 = [
                {
                    id: 1,
                    genres: [
                        { id: 4, title: "qqqq" },
                        { id: 9, title: "zzzz" },
                        { id: 8, title: "eeee" },
                    ],
                },
                {
                    id: 2,
                    genres: [
                        { id: 2, title: "qwert" },
                        { id: 4, title: "asdf" },
                        { id: 5, title: "zxxcc" },
                    ],
                },
            ];

let array2 = [6, 8];

I need to filter array1 if genre id exists in array2. So in output I should have only first element of array1.

How to do that?

2 Answers 2

1

You can use a combination of filter, some and includes:

let array1 = [{id:1,genres:[{id:4,title:"qqqq" },{id:9,title:"zzzz"},{id:8,title:"eeee" }]},
              {id:2,genres:[{id:2,title:"qwert"},{id:4,title:"asdf"},{id:5,title:"zxxcc"}]}];
let array2 = [6, 8];

let result = array1.filter(({genres}) => genres.some(({id}) => array2.includes(id)));
console.log(result);

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

Comments

0

Use the filter function.

One way to do it:

let result = array1.filter(el => {

    let output = false;
    el.genres.forEach( genre => {
        if (array2.includes(genre.id))
            output = true;
    });

    return output;
});

1 Comment

You can also add a break in the foreach loop to stop it if it already matched a value.

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.