1

I have an array of objects. I want to filter to include only objects where all of the elements in the test arrays are present in the original array.

Sample code.

const cards = [
    {
        id: "1",
        name: "J",
        tag: ["red", "yellow", "blue", "white"],
        size: ["small", "medium"],
    },
    {
        id: "2",
        name: "S",
        tag: ["red", "green", "black"],
        size: ["small", "medium"],
    },
    {
        id: "3",
        name: "K",
        tag: ["green", "purple", "brown", "white"],
        size: ["large"],
    }

Test arrays

const sizeArray = ["medium", "small"];
const tagArray = ["red", "black"];

I want the filtered array to only include the second object.

I've tried with filter, includes and no luck looking over many other answers to similar questions.

Thanks a lot.

1
  • 4
    .filter with two calls to .every as in sizeArray.every(s => obj.size.includes(s)) && (the same for tagArray) Commented Jun 26, 2020 at 23:12

1 Answer 1

3

I'm guessing this might be what you need:

const cards = [
    {
        id: "1",
        name: "J",
        tag: ["red", "yellow", "blue", "white"],
        size: ["small", "medium"],
    },
    {
        id: "2",
        name: "S",
        tag: ["red", "green", "black"],
        size: ["small", "medium"],
    },
    {
        id: "3",
        name: "K",
        tag: ["green", "purple", "brown", "white"],
        size: ["large"],
    }
];

const sizeArray = ["medium", "small"];
const tagArray = ["red", "black"];
// filtering the cards array
const filltered = cards.filter(ch => {
    // according have every size in sizeArray and
    // every tag in tagsArray
    return sizeArray.every(size => ch.size.includes(size))
        && tagArray.every(tag => ch.tag.includes(tag));
});

console.log(filltered);
Sign up to request clarification or add additional context in comments.

Comments

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.