NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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.

1      

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

2      

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.

2      

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

2      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.