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?
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With