Creating list of unique elements from an array

using the Menu App lessons as an example, if I have an array in which certain elements in each item are unique and others are not, how do I generate a list of just the unique elements. For example, I just want a list of the unique names;

struct DataService {
    
   
 func getData() -> [MenuItem] {
        
        return [MenuItem(name: "Onigiri", price: "2.99", imageName: "onigiri"),
                MenuItem(name: "Meguro Sushi", price: "6.99", imageName: "meguro-sushi"),
                MenuItem(name: "Tako Sushi", price: "5.99", imageName: "tako-sushi"),
                MenuItem(name: "Onigiri", price: "1.99", imageName: "onigiri"),
                MenuItem(name: "Meguro Sushi", price: "5.99", imageName: "meguro-sushi"),
                MenuItem(name: "Tako Sushi", price: "4.99", imageName: "tako-sushi"),
                ]
    }
**strong text**
Thanks,

Does the order matter? If not, you can throw everything into a Set and then turn it back into an array of just the unique items. (You will need to make sure that MenuItem conforms to the Hashable protocol in order for this to work.)

let uniqueMenuItems = Array(Set(DataService().getData()))

If the order does matter, you will need to do it a bit differently. (Again, however, MenuItem needs to conform to Hashable.)

extension DataService {
    func getUniqueMenuItems() -> [MenuItem] {
        let menuItems = getData()
    
        var ss: Set<MenuItem> = []
        return menuItems.filter {
            //inserting into a Set returns a tuple that has a member
            // called inserted that is false if the item already existed
            // in the Set
            //we can use this in a standard filter to only get the items
            // that are unique
            ss.insert($0).inserted
        }
    }
}

If, for some reason, neither of these methods will work, you will just have to loop through each item and manually figure out if it’s unique or not.

Thanks for the help.