[英]Filtering duplicates from two arrays
我正在嘗試從兩個 arrays 中過濾重復...
responseData.posts 和 fbFormattedPosts 都是 post 對象的 arrays。 一些帖子出現在 arrays 中,具有相同的“postId”。 我想將我的 state 設置為包含 responseData.posts 的所有帖子的數組...然后我想將 fbFormattedPosts 添加到該數組中 - 但我不想包含具有相同“postId”的 fbFormattedPosts。
我使用 useState function 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。
按照您的邏輯,應根據responseData.posts
中缺少的postId
過濾fbFormattedPosts
,因此您只需查找匹配項(例如,使用某些方法,如Array.prototype.find()
或Array.prototype.some()
,這將在Array.prototype.filter()
內部被評估為真並在匹配時立即退出)並且不要忘記傳播過濾器的結果(使用...
):
setPosts([
...responseData.posts,
...fbFormattedPosts
.filter(fbPost =>
!responseData.posts
.find(post =>
post.postId == fbPost.postId
)
)
])
你的主要想法是正確的,但你沒有以正確的方式去做。 您需要在添加之前過濾您的fbFormattedPosts
。 Array.every
測試數組中的所有元素是否通過提供的 function 實現的測試。 Array.filter
剪切every
返回false
的元素
setPosts([ ...responseData.posts, fbFormattedPosts.filter(fbPost => {
return responseData.posts.every(resPost => {
return fbPost.postId !== resPost.postId
})
})])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.