Good evening,
I have a list / array of movies that I need to filter using two values (published and category). The current code allows a user to filter movies that has both values selected. However the problem I want to fix, is if;
- A user select for example "Action", it should return all movies with category action.
- Or another scenario where a user select "1999", show all movies published that year.
- It shouldn't lose the current functionality either, as i want to allow user to filter both single values and combined.
Current code here: https://codesandbox.io/s/focused-sun-2lkfx?file=/src/App.js
I have seen examples for filtering a specific value, but in a scenario where user can specify something and add another filter to it, i don't know how to approach it.
CodePudding user response:
Here is an example of how you should filter an array with 2 values.
I also forked the sandbox example. https://codesandbox.io/s/nifty-benji-p0n9m?file=/src/App.js
Now it should work as you expected.
movies.filter((movie) => {
return (
isDateSelected(movie, filterPublished) &&
isCategorySelected(movie, filterCategory)
);
});
CodePudding user response:
You have messed something up in your useEffect, overwriting the result variable.
I have fixed it for you in a sandbox fork.
useEffect(() => {
//Filter options updated so apply all filters here
const result = array
.filter((item) =>
filterCategory.length ? filterCategory.includes(item.category) : item
)
.filter((data) =>
filterPublished.length ? filterPublished.includes(data.published) : data
);
setFilteredArray(result);
}, [filterPublished, filterCategory]);