Home > other >  How can I filter array while typing
How can I filter array while typing

Time:07-11

Like with my solution, I have to type "Back-End Developer" to get filter results. Can I just show results while typing "back" or "backend"? Even if I don't type the "-" filter doesn't work.

I guess I have to use some and toLowerCase but I don't know where to use it.

const Positions = ({ positions }: DataProps) => {
  const [selectLocation, setSelectLocation] = useState<any>('');
  const [selectJobType, setSelectJobType] = useState<any>('');
  const [filtered, setFiltered] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState<any>('');

  useEffect(() => {
    if (positions.length > 0) {
      let newList = [...positions];
      if (searchTerm) {
        newList = newList.filter((i) => i.position === searchTerm);
      }

      if (selectJobType) {
        newList = newList.filter((i) => i.position === selectJobType);
      }

      if (selectLocation) {
        newList = newList.filter((i) => i.location === selectLocation);
      }

      setFiltered(newList);
    }
  }, [positions, searchTerm, selectJobType, selectLocation]);

  return (
    <>
      <div>
        <input
          type='search'
          placeholder='Search'
          onChange={(e) => setSearchTerm(e.target.value)}
        />

        <Select
          defaultValue={selectLocation}
          onChange={setSelectLocation}
          options={locations}
          instanceId={'1'}
          placeholder='Location'
        />
      </div>

      <Select
        defaultValue={selectJobType}
        onChange={setSelectJobType}
        options={jobs}
        placeholder='Job Type'
        instanceId={'2'}
      />

      {positions?.map((position: any) => (
        <SinglePosition
          category={position.category}
          type={position.type}
          location={position.location}
          position={position.position}
          key={position._id}
        />
      ))}
    </>
  );
};

CodePudding user response:

Do not need to use the === operator just use the includes method

 useEffect(() => {
  if(positions.length > 0) {
     let newList = [...positions];
     if(searchTerm) {
        newList = newList.filter(i => i.position.toLowerCase().includes(searchTerm.toLowerCase()));
     }
     if(selectJobType) {
        newList = newList.filter(i => i.position.toLowerCase().includes(selectJobType.toLowerCase()));
     }
     if(selectLocation) {
        newList = newList.filter(i => i.location.toLowerCase().includes(selectLocation.toLowerCase()));
     }
     setFiltered(newList);
  }
}, [positions, searchTerm, selectJobType, selectLocation]);
  • Related