[英]How would you compare two arrays and filter between the two arrays?
So my first state sortedFavorites: 所以我的第一个状态为收藏夹:
This is my second state watchedFilter: 这是我的第二个状态watchedFilter:
So sortedFavorites state contains everything watchedFilter state contains, what I want to do is that compare the two arrays and filter out everything which both sortedFavorites and watchedFilter have in common. 因此sortedFavorites状态包含watchedFilter状态包含的所有内容,我要做的是比较两个数组并过滤出sortedFavorites和watchedFilter都具有的所有内容。 So I don't want any of the movies in watchedFilter to be in sortedFavorites. 因此,我不希望watchedFilter中的任何电影都在sortedFavorites中。
For example: sortedFavorites= {1,2,3,4,5} watchedFilter={1,2,3} The result I desire is: sortedFavorites={4,5} 例如:sortedFavorites = {1,2,3,4,5} watchedFilter = {1,2,3}我想要的结果是:sortedFavorites = {4,5}
This is what I tried but it doesn't do anything: 这是我尝试过的,但没有做任何事情:
filterFavorites = () => {
let showFavorites = this.state.sortedFavorites.filter(fav => !this.state.watchedFilter.includes(fav))
this.setState(state => ({
...state,
...{ sortedFavorites: showFavorites }
}));
}
You could create a new array with all entries from sortedFavorites
that are not in watchedFilter
. 你可以创建从所有条目的新数组sortedFavorites
不在watchedFilter
。
Since there are separate objects in both arrays includes
will not work, because that will check for exact object references . 由于两个数组中都有单独的对象,所以includes
将不起作用,因为它将检查确切的对象引用 。 You can check if the id
is the same instead: 您可以改为检查id
是否相同:
filterFavorites = () => {
this.setState(previousState => {
const sortedFavorites = previousState.sortedFavorites.filter(
fav => !previousState.watchedFilter.some(w => w.id === fav.id)
);
return { sortedFavorites };
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.