Search code examples
javascriptarraysobject

Filter array of objects with multiple conditions


I have an array of objects that looks like this:

const pets = [
    {name: "Dog", tags: "ground, pet, active"},
    {name: "Cat", tags: "ground, pet, relaxed"},
    {name: "Fish", tags: "water, pet, exotic"},
] 

I want to filter out the array based on the tags key from a given keyword:

const search = "ground"
const result = pets.filter((pet) => pet.tags.includes(search)) 

It outputs this:

[
  { name: 'Dog', tags: 'ground, pet, active' },
  { name: 'Cat', tags: 'ground, pet, relaxed' }
]

What if I want to filter out the pets array with multiple keywords on the tags like this:

const search = ["ground", "active"]

In theory, only the { name: 'Dog', tags: 'ground, pet, active' } should be found given the two keywords.

Any ideas how can I achieve something like this?


Solution

  • You can try using Array.prototype.every() that checks if all elements in the array pass the test implemented by the provided function:

    const pets = [
        {name: "Dog", tags: "ground, pet, active"},
        {name: "Cat", tags: "ground, pet, relaxed"},
        {name: "Fish", tags: "water, pet, exotic"},
    ] 
    
    
    const search = ["ground", "active"];
    
    const result = pets.filter((pet) => {
        //split the tags string into an array
        const petTags = pet.tags.split(',').map(tag => tag.trim());
        //check if every search keyword is included in the petTags array
        return search.every((keyword) => petTags.includes(keyword));
    });
    
    console.log(result);