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
You can try using
Array.prototype.every()
that checks if all elements in the array pass the test implemented by the provided function: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)
and use array.some.. using some will reduce the number of loops in best cases
Another alternative approach is: