How to check if a string is included in a list

I’m attempting to check if the value (string) of a dropdown filter is included in this string of property "sales" this string could have a list of items or just include one. My includes condition works as expected when it’s only 1 item in the string, but when it’s multiple it fails.

Here is my code snippet:

const data = [
{ id: 123,
  sales: "online"
}, 
{
id: 231,
sales: "retail, online, mall"
},
{
id: 311,
sales: "retail"
}
]

const selectedItem = "retail"

for (const item of data) {

if (selectedItem.length > 0 && selectedItem.includes(item.sales)) {
console.log('true')
} else {
console.log('false')
}

}

I’m expecting my outcome to be:

false,
true,
true

because in the 2nd index in my array retail, online, mall still includes the word "retail"

How can I check if this is included for both possible conditions?

>Solution :

You may use string test() here to check the entire CSV list:

const data = [
{ id: 123,
  sales: "online"
}, 
{
id: 231,
sales: "retail, online, mall"
},
{
id: 311,
sales: "retail"
}
]

const selectedItem = "retail"

for (const item of data) {
    var regex = new RegExp("\\b" + selectedItem + "\\b");
    if (regex.test(item.sales)) {
        console.log('true')
    }
    else {
        console.log('false')
    }
}

Leave a Reply