Skip to content
Advertisement

React: Filter table data with multiple column values

I have the following an array object data. I wanted to filter it’s data when a user provide either title, category or published values from an input. I can only filter the data only with title value. How can I make it to category and published values as well? here is my code. `

const data = [
  { id: 1, title: "Hunger games 2", category: "Action", published: "2013" },
  { id: 2, title: "Iron Man", category: "Action", published: "2013" },
];

const [searchValue, setSearchValue] = useState(""); //searchValue is an input value

const DisplayData = data
    ?.filter((row) => row?.title?.match(new RegExp(searchValue, "i")))
    ?.map((items) => {
      return (
        <>
          <tr key={items.id}>
            <td className="text-center">{items.title}</td>
            <td>{items.category}</td>
            <td>{items.published}</td>
          </tr>
        </>
      );
    });

Advertisement

Answer

You can add “or” conditions to your filter:

const DisplayData = data
    ?.filter((row) => row?.title?.match(new RegExp(searchValue, "I")) || 
      row?.category?.match(new RegExp(searchValue, "I")) ||
      row?.published?.match(new RegExp(searchValue, "I"))
    )
    ?.map((items) => ...
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement