Home > Back-end >  How can I apply multiple filter to array
How can I apply multiple filter to array

Time:07-10

I can just filter by input text that comes from "searchTerm" state. but I want to include "selectedOption" dropdown input to the filter. how can I use multiple filters for an array?

btw I'm using react-select for dropdown menu.

const Positions = ({ positions }: dataProps) => {

const options: any = [
  { value: "Canada", label: "Canada" },
  { value: "Italy", label: "Italy" },
];

const [selectedOption, setSelectedOption] = useState(null);

  const [searchTerm, setSearchTerm] = useState("");

  const filteredPositions = useMemo(() => {
    if (!searchTerm) return positions;
    return positions.filter(({ id, ...other }: any) => {
      const lowerCasedSearchTerm: string = searchTerm.toLowerCase();

      return Object.values(other)
        .map((v: any) => v.toLowerCase())
        .some((v: any) => v.includes(lowerCasedSearchTerm));
    });
  }, [searchTerm, positions]);

  return (

             <input
                  type="search"
                  placeholder="Search"
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
            <div className={styles.positions__item}>
              <Select
                defaultValue={selectedOption}
                onChange={setSelectedOption}
                options={options}
              />
              <Select
                defaultValue={selectedOption}
                onChange={setSelectedOption}
                options={options}
              />

   {filteredPositions?.map((position: any, index: any) => (
            <div key={position.position}>
              <SinglePosition
                category={position.category}
                type={position.type}
                position={position.position}
              />
            </div>
          ))}

CodePudding user response:

Check this please.

const filteredPositions = useMemo(() => {
if (!(searchTerm || selectedOption)) return positions;
return positions.filter(({ id, ...other }: any) => {
  const lowerCasedSearchTerm: string = searchTerm.toLowerCase();

  return Object.values(other)
    .map((v: any) => v.toLowerCase())
    .some((v: any) => v.includes(lowerCasedSearchTerm) || v.includes(selectedOption));
});
 }, [searchTerm, positions, selectedOption]);

CodePudding user response:

Try this:

const filteredPositions = useMemo(() => {
    if (!searchTerm) return positions;
    return positions.filter(({ id, ...other }: any) => {
      const lowerCasedSearchTerm: string = searchTerm.toLowerCase();

      return Object.values(other)
        .map((v: any) => v.toLowerCase())
        .some((v: any) => v.includes(lowerCasedSearchTerm) || v.includes(selectedOption.value.toLowerCase()));
    });
  }, [searchTerm, positions]);

Since, we are converting everything into lowercase, we need to convert selected option as well.

  • Related