0

I have a search bar that filters through an array containing one object:


const [termList, setTermList] = useState([{term_name: 'Name', definition: 'This is a glossary term'}]);

const filtered = termList.filter((term) =>
    Object.values(term).some(
      (val) =>
        typeof val === "string" &&
        term.term_name.includes(searched.toLowerCase())
    )
  );

return (
    <div>
        <input
          type="text"
          value={searched}
          onChange={(ev) => setSearched(ev.target.value)}
        />
      </div>
      <div className="termList">
        {filtered.map((term) => (
            <div>
              <div>{term.term_name.toLowerCase()}</div>
              <div>{term.definition}
            </div>
        ))}
    </div>
  );

When I filter through the list, however, if I type into the search bar the letter 'n', my filtered list is empty even though the only object inside the array has a name that begins with an 'n'.

Even more odd is that when I type into the search bar 'a', 'am', or 'ame' my filtered list includes the object.

2 Answers 2

1

You are making you searched lowercase but not term.term_name, 'n' is not in 'Name', 'N' is. You need to do

term.term_name.toLowerCase().includes(searched.toLowerCase())
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah this worked, but can you explain a bit more of what that fixed?
term.termName is Name. It consists of four characters: N,a,m,e. When you check if ['N','a','m','e'].includes('n') it correctly returns false. If you first make term.termName lowercase, it checks if ['n','a','m','e'].includes('n') and returns true
1

you can also do like this, instead of making filtered function

const [termList, setTermList] = useState([{term_name: 'Name', definition: 'This is a glossary term'}]);

return (
    <div>
        <input
          type="text"
          value={searched}
          onChange={(ev) => setSearched(ev.target.value)}
        />
      </div>
      <div className="termList">
        {termList.filter(item => (search ? item.term_name?.toLowerCase().includes(searched.toLowerCase()) : true)).map((term) => (
    <div>
      <div>{term.term_name.toLowerCase()}</div>
      <div>{term.definition}
    </div>
))}
    </div>
  );

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.