0

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) => (
1
  • array.some may help Commented Mar 18, 2022 at 12:37

5 Answers 5

2

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());
   }
};
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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"))

Comments

1

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)))

here is a little example

Comments

1

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
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.