I have an array of Objects, and every object has an array of strings (tags), I need to filter the array of objects based on another array.
data: [
{
"id":"Nerium",
"tags":["CMS Selection", "Experience Design", "Development","UX"],
"featured":0
},
{
"id":"WesternDigital",
"tags":["Digital Strategy", "Analytics", "Example"],
"featured":1
},
{
"id":"Example",
"tags":["Example", "Analytics", "UX"],
"featured": 0,
},
I need to filter the above data based on an Array like this:
activeTags: ['UX', 'Example']
And the objects of Data I filter need to specifically have the values inside activeTags, in this case if for example an Object has ‘UX’ but it doesn’t have ‘Example’, I don’t return it.
Expected output:
data: [{
"id": "Example",
"tags": ["Example", "Analytics", "UX"],
"featured": 0,
}]
Or it should return every Object that has tags that specifically have the values in activeTags
>Solution :
This should work
const data = [
{
id: "Nerium",
tags: ["CMS Selection", "Experience Design", "Development", "UX"],
featured: 0,
},
{
id: "WesternDigital",
tags: ["Digital Strategy", "Analytics", "Example"],
featured: 1,
},
{
id: "Example",
tags: ["Example", "Analytics", "UX"],
featured: 0,
},
];
const activeTags = ["UX", "Example"];
const filtered = data.filter(({ tags }) =>
activeTags.every((tag) => tags.includes(tag))
);
console.log(filtered);
you can use .every to check that the object has all the active tags