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 https://stackoverflow.com/questions/29727618/find-duplicate-elements-in-array-using-swift – xmhafiz Jun 05 '17 at 09:01
-
@hafiz he don't like to find duplicate elements (if I understood him) – user3441734 Jun 05 '17 at 09: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

- 40,517
- 4
- 31
- 51
I don't know how to do that specifically for swift but in general you can check every string of the array with any string after it in the array (just like the sorting algorithm) and if you find that a string is equal to another one then you have a double string in your array

- 13
- 3
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)

- 16,722
- 2
- 40
- 59
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,887
- 11
- 26
-
1While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Badacadabra Jun 05 '17 at 14:02
I would add it to a set of strings from your title then compare the count of both, if count is equal then there are no duplicates, if set count less that mean there are two titles that equal

- 442
- 4
- 12