-1

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

Mat Mol
  • 73
  • 1
  • 1
  • 9

2 Answers2

2

I haven't tested, but I think the following should work:

const result = data.filter( record =>
    activeTags.every( tag =>
        record.tags.includes( tag )
    )
);

filter() returns array with only elements that pass its function test. every() returns true only if every element passes its function test. includes() will test if the element is included in the record.tags array.

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
2

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

Jacob Stephenson
  • 544
  • 3
  • 13