1

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?

0

1 Answer 1

2

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.

Array.prototype.some()

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.