Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get distinct elements in an array by object property

I have an array of object. I want to get distinct elements in this array by comparing objects based on its name property

class Item {
var name: String
init(name: String) {
    self.name = name
}
}
let items = [Item(name:"1"), Item(name:"2"), Item(name:"1"), Item(name:"1"),Item(name:"3"), Item(name:"4")]

result:

let items = [Item(name:"1"), Item(name:"2"),Item(name:"3"), Item(name:"4")]

how can I do this in swift?

like image 584
Hashem Aboonajmi Avatar asked May 30 '16 04:05

Hashem Aboonajmi


People also ask

How do you find the unique elements of an array?

In Java, the simplest way to get unique elements from the array is by putting all elements of the array into hashmap's key and then print the keySet(). The hashmap contains only unique keys, so it will automatically remove that duplicate element from the hashmap keySet.

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

Here is an Array extension to return the unique list of objects based on a given key:

extension Array {
    func unique<T:Hashable>(by: ((Element) -> (T)))  -> [Element] {
        var set = Set<T>() //the unique list kept in a Set for fast retrieval
        var arrayOrdered = [Element]() //keeping the unique list of elements but ordered
        for value in self {
            if !set.contains(by(value)) {
                set.insert(by(value))
                arrayOrdered.append(value)
            }
        }

        return arrayOrdered
    }
}

For your example you can do:

let uniqueBasedOnName = items.unique{$0.name}
like image 165
Ciprian Rarau Avatar answered Sep 28 '22 10:09

Ciprian Rarau