Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter nested array in object based on specific values of another array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading