Includes method working for only one Value but i want to filter multiple values with comma like this "mahmoud, faizan" i'll get these value from user input
json Data
[{
"text": "adnan hassan"
}, {
"text": "adnan hassan mahmoud",
}, {
"text": "adnan hassan faizan",
}]
Filter Function
const filterFunction = (a) => {
if(includeKeyword)
return a.text.includes("mahmoud")
}
Filter Function with map render
postRes.filter(filterFunction).map((data, index) => (
I gave you two return statements to choose from, depending on if you want to match all parts or at least one part out of what was typed in:
const filterFunction = (a) => {
if(includeKeyword)
const parts = userInput.split(",");
// if you need the returned element to match *all* parts (AND)
return parts.every(p => a.text.includes(p.trim());
// if you need it to match *at least one* part (OR)
return parts.some(p => a.text.includes(p.trim());
}
};
for your senario you can customize the filter function to get a second parameter and use array.some:
const filterFunction = (a, searchArray) => {
if (searchArray.some((v) => a.text.includes(v))) {
return a;
}
};
const result = postRes.filter((item) => filterFunction(item, ["mahmoud", "faizan"]));
console.log("result ", result);
if you like to solve by javascript methods, like many people pointed out
if (["mahmoud", "faizan"].some((v) => a.text.includes(v))) {
return a;
}
if you like regular expression, do this way
if(a.text.match(/(mahmoud|faizan)/)){
return a
}