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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.