UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.