-1

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?

2

3 Answers 3

4

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I'd create the tags array before checking with every(). Otherwise you're doing the same thing for every search word
Answered multiple times in either case...
1

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);

Comments

-1

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)) )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.