我正在尝试从两个数组中过滤重复项...
responseData.posts 和 fbFormattedPosts 都是 post 对象的数组。有些帖子出现在两个数组中,具有相同的“postId”。我想将我的状态设置为包含所有responseData.posts帖子的数组...然后我想将fbFormattedPosts添加到该数组 - 但我不想包含具有相同“postId”的fbFormattedPosts。
我使用 useState 函数 setPosts 设置“帖子”useState 数组。如果我对它们使用展开运算符,它们都会添加每个数组中的所有帖子。这可行,但我最终得到了重复的帖子。
//set All Posts
setPosts([ ...responseData.posts, ...fbFormattedPosts])
因此,我尝试比较 Id 以将其过滤掉。
setPosts([ ...responseData.posts, fbFormattedPosts.forEach(fbPost => {
responseData.posts.filter(resPost => {
if(fbPost.postId !== resPost.postId ){
return fbPost
}
})
})])
显然这不起作用...现在我根本没有收到任何帖子。甚至没有responseData.posts。
最佳答案
按照你的逻辑,fbFormattedPosts
应该根据responseData.posts
中缺少的postId
进行过滤,所以你需要的只是查找匹配(例如使用一些方法,如 Array.prototype.find() 或 Array.prototype.some() ,它们将被评估为 true 并在匹配时立即退出) Array.prototype.filter()
并且不要忘记传播过滤器的结果(使用 ...
):
setPosts([
...responseData.posts,
...fbFormattedPosts
.filter(fbPost =>
!responseData.posts
.find(post =>
post.postId == fbPost.postId
)
)
])
关于javascript - 过滤两个数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61717585/