Home > database >  filtering through array of strings doesn't include the first character
filtering through array of strings doesn't include the first character

Time:06-29

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.

CodePudding user response:

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

CodePudding user response:

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