2

I have a list of objects like this.

results = [
   { id: 1, 
     status : "Active"
     // Some other fields
     tags : [{val: 'IGM', color: 'light-success' },
             {val: 'Gated Out', color: 'light-primary' },
            ]   
   },
   // ...
]

now I want to filter objects in relation to tags, the input to filter the list is also in the form of an array using multi-select input.

like

[{value: 'Gated Out', label: 'GATED OUT'},  .. ]

I'm able to filter data of other fields but not the tags because other fields are in strings and tags are an Array.

But now How can I modify this to work with the array as well.

I'm using that approach;

  const handleTagsFilter = (value) => {
    let updatedData = []

    const dataToFilter = () => {
      if (
        status.length ||
        custom_tags.length
      ) {
        return filteredData
      } else {
        return results
      }
    }

    setCustomTags(value)
    if (value.length) {
      updatedData = dataToFilter().filter((item) => {
        const startsWith = item.status.toLowerCase().startsWith(value.toLowerCase())

        const includes = item.status.toLowerCase().includes(value.toLowerCase())

        if (startsWith) {
          return startsWith
        } else if (!startsWith && includes) {
          return includes
        } else return null
      })
      setFilteredData([...updatedData])
      setCustomTags(value)
    }
  }

That function works with filtering strings like we have the status field to Active than this work, But I'm not sure how I can modify it to work with the array as well.

1 Answer 1

1

Maybe something like:

let search_str = 'abc'.toLowerCase();
let filtered_results = results
  .map(v => v.tags.filter(_v => _v.val.toLowerCase().includes(search_str)))
  .filter(v => v.length)
  .reduce((a, b) => a.concat(...b), [])
Sign up to request clarification or add additional context in comments.

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.