Combine multiple filtres

Viewed 27

I stack into multiple filters right now is

const DashboardPage = () => {
  const { device } = useSelector((state) => state.device);
  const [q, setQ] = useState("");
  const [searchParam] = useState(["deviceName"]);
  const [filterParam, setFilterParam] = useState(["All"]);      
  function search(device) {
    return device.filter((item) => {
      if (filterParam == "All") {
        return searchParam.some((newItem) => {
          return (
            item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
          );
        });
      } else if (item.deviceStatus == filterParam) {
        return searchParam.some((newItem) => {
          return (
            item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
          );
        });
      }
    });
  }





 return( <input type="search"
                  value={q}
                  onChange={(e) => setQ(e.target.value)}/>
           search(device).map((devicedetails) => {}) )

Unfortunately, I cannot use more than a filter per search. The fixed problem may be simple, but I cannot understand it now.

final scope see

1 Answers

To use multiple filters you could do something like this:

const DashboardPage = () => {
    const {device} = useSelector((state) => state.device);
    const [q, setQ] = useState("");
    const [searchParam] = useState(["deviceName"]);
    const [filterParam, setFilterParam] = useState(["All"]);

    function search(device) {
        // Declare a filtered array and filter the items once
        let filteredDevices = device.filter((item) => {
            if (filterParam == "All") {
                return searchParam.some((newItem) => {
                    return (
                        item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
                    );
                });
            }
        });
        // Filter the items again using the other filter.
        filteredDevices = filteredDevices.filter((item) => {
            if (item.deviceStatus == filterParam) {
                return searchParam.some((newItem) => {
                    return (
                        item[newItem].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
                    );
                });
            }
        });
        return filteredDevices;
    }

    // ...
}

Since your code is not a fully working minimal example I'm not 100% sure that the solution I've offered will work but it should get you most of the way there. Just filter your list with both filters before returning it rather than only filtering it one way and returning it.

Related