BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Check if the array of objects contains another object based on its id.

Forums > Swift

Hey guys.

I have two arrays. One is the empty one. The other one contains many objects, some of them have the same "id" parameter but different "quantity" parameter so the are unique in a way.

To the new empty array I would like to append only objects based on id, so they wont repeat. Normal .contain will include two objects with the same id but with different quantity.

How can I make that happen? Thanks for help.

3      

this looks like it might do what you are looking for:

https://stackoverflow.com/questions/34709066/remove-objects-with-duplicate-properties-from-swift-array

May not be the more efficient way of doing things and maybe someone else may have a better idea but my thinking is:

1) create new array usng the normal .contains which will bring in the values with the ID that you want but with the duplicates where you have different quantieis 2) use on the solutions in the link to remove the duplicates

4      

Hi, you can use the contains(where: method and check based on id. If you have a lot of items, then it would make sense to use something like Set to keep tracks of IDs already added, because this is much faster than doing contains on an array.

4      

        if let ix = paragraphs?.firstIndex(where: { $0.id == paragraphToRemove.id }) {
            paragraphs?.remove(at: ix)
        }

4      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.