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) => (
CodePudding user response:
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());
}
};
CodePudding user response:
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);
CodePudding user response:
Filter function returns a boolean. You can set this boolean with a loop :
Example :
const base = [{
"text": "adnan hassan"
}, {
"text": "adnan hassan mahmoud",
}, {
"text": "adnan hassan faizan",
}]
function myFilter(base,query){
const queries = query.split(",")
return base.filter((a)=>{
let doReturn = false;
queries.forEach((q)=>{
if(a.text.includes(q)){
doReturn = true;
}
})
return doReturn;
});
}
console.log(myFilter(base,"faizan,hector,mickey,mahmoud"))
CodePudding user response:
create a array from your search text with split(','):
const searchParams = searchText.split(',');
then filter your data array like this:
test is your data array searchParams is the list of search parameters:
test.filter(t => searchParams.some(v => t.text.includes(v)))
CodePudding user response:
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
}