Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading