Home > OS >  Enabling multiple filters for a single array
Enabling multiple filters for a single array

Time:10-17

in my application, there are two types of filters, category and country. However, I am not able to get them to be applied at the same time. For example, I only want the intersection of Category: SaaS Country: Singapore.

Any advice?

  const loadData = props.load 
  const [card, setCard] = useState(loadData)
  const [searchPhrase, setSearchPhrase] = useState("")
  const search = (event)=>{
    const matchedUsers = loadData.filter((card)=>{
      return card.title.toLowerCase().includes(event.target.value.toLowerCase())
    })
    setCard(matchedUsers)
    setSearchPhrase(event.target.value)
  }
  const filterCountry = (event)=>{
    const filteredCards = loadData.filter((card)=>{
      return card.country.includes(event.target.value)
    })
    setCard(filteredCards)
  }
  const filterCat = (event)=>{
    const filteredCards = loadData.filter((card)=>{
      return card.cat.includes(event.target.value)
    })
    setCard(filteredCards)
  }

CodePudding user response:

You can change your filter condition to check if the value is in all your considered types

const result = yourData.filter(item => item.country.includes(YOURPHRASE) || item.cat.includes(YOURPHRASE))

CodePudding user response:

you can pass the filtered array as a parameter to the filtering functions :

 const search = (event)=>{
       const matchedUsers = loadData.filter((card)=>{
          return card.title.toLowerCase().includes(event.target.value.toLowerCase())
        })
        setSearchPhrase(event.target.value);
return matchedUsers
      }
      

const filterCountry = (event,array)=>{
   
    return array.filter((card) => card.country.includes(event.target.value);

  }

 const filterCat = (event,array)=>{
        return array.filter((card) => card.cat.includes(event.target.value);
  }
        
     useEffect(() => {
        
        let result = matchedUsers();
        result = filterCountry(result);
        result = filterCat(result);
        setArrayToFilter(result);
    }, [searchPhrase]);
    
 
  • Related