Search code examples
reactjsarraysobjectfilter

Filtering array by input value react


I have a little problem with filtering my array.

I want display a product filtered by input value with a name or platform or something other value. With name is no problem, but i don't know how to do it with platforms.

Bottom is my logic and file with products, txh very much for help

live: live

repo: repo

const [inputText, setInputText] = useState('')

const inputHandler = e => {
        const text = e.target.value.toLowerCase()
        setInputText(text)
}

const filteredData = PRODUCT_LIST.filter(el => {
        if (inputText === '') {
            return
        } else {
            return el.name.toLowerCase().includes(inputText)
        }
})
const PRODUCT_LIST = [
    {
        id: 'gow',
        name: 'God of War',
        developer: 'Santa Monica Studio',
        category: 'games',
        platform: 'PlayStation 4',
        version: 'PL',
        price: 39,
    },]

Solution

  • You need to make a conditional check.

    First, check whether the search text matches the name; if it fits, return the list. If not, then check whether it matches the platform.

    const filteredData = PRODUCT_LIST.filter(el => {
    
          const findByName = el?.name?.toLowerCase().includes(inputText);
          const findByPlatform = el?.platform?.toLowerCase().includes(inputText);
    
            if (inputText === '') {
                return
            } else {
                return findByName || findByPlatform
            }
    })