i have the following list of UITextField:
let list = [(name1TextField, phone1TextField), (name2TextField, phone2TextField), (name3TextField, phone3TextField), (name4TextField, phone4TextField), (name5TextField, phone5TextField)]
i'm trying to find phones duplicates and print them out
EDIT
e.g. (tuples could be empty)
list = [("john", "555-444-333"), ("james", "555-444-333"), ("",""), ("bob", "333-222-111"), ("nancy", "222-111-444"), ]
output 555-444-333
how can i do?
Given this
var name1TextField: UITextField!
var phone1TextField: UITextField!
var name2TextField: UITextField!
var phone2TextField: UITextField!
var name3TextField: UITextField!
var phone3TextField: UITextField!
var name4TextField: UITextField!
var phone4TextField: UITextField!
var name5TextField: UITextField!
var phone5TextField: UITextField!
And this
let list = [(name1TextField, phone1TextField), (name2TextField, phone2TextField), (name3TextField, phone3TextField), (name4TextField, phone4TextField), (name5TextField, phone5TextField)]
let repeatedPhones = list
.flatMap { $0.1?.text }
.reduce([String:Int]()) { (var dict, phone) -> [String:Int] in
dict[phone] = (dict[phone] ?? 0) + 1
return dict
}
.filter { $0.1 > 1 && !$0.0.isEmpty }
.map { $0.0 }
Using dictionary
to record how many time you see a phone number:
var dict = [String: Int]()
And then go thru the whole list:
for (_, phone) in list {
if let count = dict[phone] {
dict[phone] = count + 1
} else {
dict[phone] = 1
}
}
After this you will have a dictionary which contains the phone number and the count of each phone number appear in the list
for item in dict {
if item.1 > 1 {
print(item.0)
}
}
This method has a time complexity: O(2n)
And this question looks like a duplicate of Find Duplicate Elements In Array Using Swift
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