skip to Main Content

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?

3

Answers


  1. 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);
    Login or Signup to reply.
  2. I suggest you to start from chaging the pet data format, anyway the tags are array of strings .. so instead of keeping it as string .. store it an array (To Avoid split everytime)

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

    and use array.some.. using some will reduce the number of loops in best cases

    pets.filter((pet) => search.some(r=>pet.tags.includes(r)) )
    
    Login or Signup to reply.
  3. Another alternative approach is:

    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) => {
        const petTags = pet.tags.split(', ');
        for (const keyword of search) {
            if (!petTags.includes(keyword)) {
                return false; 
            }
        }
      return true; 
    });
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search