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?
CodePudding user response:
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')
}
}
CodePudding user response:
Isn't it enough to simply switch around the selectedItem.includes(item.sales)
to item.sales.includes(selectedItem)
?
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 && item.sales.includes(selectedItem)) {
console.log('true')
} else {
console.log('false')
}
}
CodePudding user response:
I would seperate your string on line 7 to "retail", "online", "mall". It seems you are trying to call all strings that have "retail" to be true. If that is the case, I think it may work.