簡體   English   中英

過濾來自兩個 arrays 的重復項

[英]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
        })
    })])

如果你想以一種功能性的方式傳播數組,你應該使用 Array filtersome

setPosts([ ...responseData.posts, ...fbFormattedPosts.filter(fbPost => (
            !responseData.posts.some(resPost =>
                fbPost.postId === resPost.postId 
            )
        ))])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM