简体   繁体   中英

Filtering duplicates from two arrays

I am trying to filter duplicates from two arrays...

responseData.posts and fbFormattedPosts are both arrays of post objects. Some posts appear in both arrays with the same 'postId'. I'd like to set my state to an array containing all posts of responseData.posts... then I want to add the fbFormattedPosts to that array - But I don't want to include the fbFormattedPosts that have the same 'postId'.

I set my 'posts' useState array using the useState function setPosts. If I use the spread operator for them, they both add all the posts from each array. This works, but I end up with duplicate posts.

//set All Posts
        setPosts([ ...responseData.posts, ...fbFormattedPosts])

So, I am trying to compare the Ids to filter them out.

setPosts([ ...responseData.posts, fbFormattedPosts.forEach(fbPost => {
            responseData.posts.filter(resPost => {
                if(fbPost.postId !== resPost.postId ){
                    return fbPost
                }
            })
        })])

Obviously this doesn't work... Now I get no posts at all. Not even the responseData.posts.

Following your logic, fbFormattedPosts should be filtered based on postId missing from responseData.posts , so what you need is simply look up for matches (eg using some methods, like Array.prototype.find() or Array.prototype.some() , that will be evaluated truthy and exit immediately upon match) inside Array.prototype.filter() and don't forget to spread the result of filter (using ... ):

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

Your main idea is right but you doesn't do it in a right way. You need to filter your fbFormattedPosts before adding. Array.every tests whether all elements in the array pass the test implemented by the provided function. Array.filter cut all elements for which every return false

setPosts([ ...responseData.posts, fbFormattedPosts.filter(fbPost => {
        return responseData.posts.every(resPost => {
            return fbPost.postId !== resPost.postId
        })
    })])

If you want to spread the arrray in a functional way you should use Array filter and some :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM