Reputation: 391
I have an array of objects and I wish to filter out those objects if my filter array matches the string of a key.
// my stores
var stores = [
{
id: 1,
store: 'Store 1',
storeSells: "Belts|Handbags|Watches|Wallets"
},
{
id: 2,
store: 'Store 2',
storeSells: "Handbags|Personal Accessories|Jewelry|Eyewear|"
},
{
id: 3,
store: 'Store 3',
storeSells: "Belts|Travel|Charms|Footwear|"
},
{
id: 4,
store: 'Store 3',
storeSells: "Charms|Footwear|"
}
]
// my filters
var filters = ["Handbags","Belts"]
So, If my filters
array has handbags
and belts
. I wish to filter stores with id's 1,2 and 3
only as they contains these keywords. Can you please help me with this?
Upvotes: 1
Views: 39
Reputation: 68943
You can try with Array.prototype.filter()
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
And String.prototype.includes()
The
includes()
method determines whether one string may be found within another string, returning true or false as appropriate.
// my stores
var stores = [
{
id: 1,
store: 'Store 1',
storeSells: "Belts|Handbags|Watches|Wallets"
},
{
id: 2,
store: 'Store 2',
storeSells: "Handbags|Personal Accessories|Jewelry|Eyewear|"
},
{
id: 3,
store: 'Store 3',
storeSells: "Belts|Travel|Charms|Footwear|"
},
{
id: 4,
store: 'Store 3',
storeSells: "Charms|Footwear|"
}
]
// my filters
var filters = ["Handbags","Belts"];
var res = stores.filter(item => filters.some(i=>item.storeSells.includes(i)));
console.log(res);
Upvotes: 2