I'm trying to filter a list by tags:
const initialState = [
{id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
{id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
{id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
]
I can filter the list by name using map
and filter
, my problem is when i try to list the products by tags. Do i have to use foreach
inside of my products filter? There's another way of doing it?
Firstly to get all the tags and filter the duplicate tags from initialState. Save the array into uniqueTags.
Then compare the uniqueTags with initialState names, to create another array productTags with objects and its properties tags and products.
(Edited later) Correction:
To form the correct object, I have changed the code to:
Like that?
you can use indexOf function
You can create a Set of selected tags, and use
Array#some
to check if at least one of the tags in the Set exists in the objects' tags list: