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.
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);
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.