gpt4 book ai didi

javascript - react : apply multiple filters to array

转载 作者:行者123 更新时间:2023-12-03 06:54:02 25 4
gpt4 key购买 nike

我从 react 开始,我有一个名为 arrayToFilter 的对象数组,我想应用多个过滤器,理想情况下,当用户更改过滤器选择选项时,所有过滤器都应应用于数组,并将结果返回到过滤结果数组以显示,我已经有了每个过滤器函数和它们的常量,但我不知道如何一个接一个地应用所有过滤器......
这是我的代码:

    const [ arrayToFilter, setArrayToFilter ] = useState([ /*array of objects to apply filters to*/ ]);
const [ filteredResults, setFilteredResults] = useState([ /*array of filtered objects*/ ]);
const [ categoryOptions, setCategoryOptions ] = useState([ 1,2,3 ]);
const [ selectedCategoryOptions, setSelectedCategoryOptions ] = useState([ ]);
const [ searchName, setSearchName ] = useState('');
const [ hideVenuesWithoutDiscounts, setHideVenuesWithoutDiscounts ] = useState(true);

const filterHideVenuesWithoutDiscounts = () =>
{
if(hideVenuesWithoutDiscounts)
{
return arrayToFilter.filter(item => item.discounts.length > 0);
}
else
{
return arrayToFilter;
}
};

const filterSelectedCategoryOptions = () =>
{
return arrayToFilter.filter(item => item.category_id.includes(selectedCategoryOptions));
};

const filtersearchName = () =>
{
return arrayToFilter.filter(item => item.name.toLowerCase().indexOf(searchTerm.toLowerCase()) != -1);
};

useEffect(() =>
{
//Filter options updated so apply all filters here
},
[searchName, hideVenuesWithoutDiscounts, selectedCategoryOptions]);
注意 useEffect,afaik 这就像 vue 中的 watch 属性,我想在过滤器输入更改时触发所有过滤器

最佳答案

很简单,您可以将过滤后的数组作为参数传递给过滤函数,以便它们可以过滤过滤后的数组。
例如:

const filterHideVenuesWithoutDiscounts = (array) => {
if (hideVenuesWithoutDiscounts) {
return array.filter((item) => item.discounts.length > 0);
} else {
return array;
}
};

const filterSelectedCategoryOptions = (array) => {
return array.filter((item) => item.category_id.includes(selectedCategoryOptions));
};

const filtersearchName = (array) => {
return array.filter((item) => item.name.toLowerCase().indexOf(searchTerm.toLowerCase()) != -1);
};

useEffect(() => {
//Filter options updated so apply all filters here
let result = arrayToFilter;
result = filterHideVenuesWithoutDiscounts(result);
result = filterSelectedCategoryOptions(result);
result = filtersearchName(result);
setArrayToFilter(result);
}, [searchName, hideVenuesWithoutDiscounts, selectedCategoryOptions]);

关于javascript - react : apply multiple filters to array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64048890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com