I have an array of objects. Each object has an property called title , I want to know if two object has the same title. How to do that in swift?
-
possible duplicate stackoverflow.com/questions/29727618/…xmhafiz– xmhafiz2017-06-05 09:01:49 +00:00Commented Jun 5, 2017 at 9:01
-
@hafiz he don't like to find duplicate elements (if I understood him)user3441734– user34417342017-06-05 09:21:36 +00:00Commented Jun 5, 2017 at 9:21
5 Answers
If you want the list of objects which have the same title as another object in the array, you can do this (assuming title is a String):
var titles = Set<String>()
let duplicates = array.filter{ !titles.insert($0.title).inserted }
// note: this only lists the second and subsequent element with a given title
if you need their indexes, you can do this:
var titles = Set<String>()
let dupIndexes = array.enumerated()
.filter{ !titles.insert($1.title).inserted }
.map{$0.0}
If you want all objects where the title is duplicated (including the first one) you can refine the first approach like this:
var titles = Set<String>()
let dupTitles = Set(array.map{$0.title}.filter{!titles.insert($0).inserted})
let dupObjects = array.filter{dupTitles.contains($0.title)}
[EDIT] Swift 4 has a new Dictionary initializer that can be used for this:
let dupObjects = Dictionary(grouping:array){$0.title}
.filter{$0.value.count > 1}
.flatMap{$0.value}
In all cases, if the .count of duplicates, dupIndexes or dupObjects is > 0 hen you have at least one duplication in the array
1 Comment
var duplicateArray: [String] = []
var storedArray: [String] = []
for text in array {
if storedArray.contains(text) {
dump(text + " is a duplicate")
dupliateArray.append(text)
}
storedArray.append(text)
}
1 Comment
let s = Set(arr.map{$0.title})
print("found duplicate title?", arr.count != s.count)
in case your title doesn't conform to Hashable protocol, simply use
let s1 = Set(arr1.map{"\($0.title)"})
print("found duplicate title?", arr1.count != s1.count)