-3

i have an array in that array there are 2000 dictionary and i want to find out the duplicates in that array.

let contacts = [
    Contact(name: "siddhant",     phone: "1234"),
    Contact(name: "nitesh", phone: "1234"),
    Contact(name: "nitin",  phone: "2222"),
    Contact(name: "himanshu",   phone: "2222"),
    Contact(name: "kedar",    phone: "3333")
]

// output should be:

[
        Contact(name: "siddhant",     phone: "1234"),
        Contact(name: "nitesh", phone: "1234"),
        Contact(name: "nitin",  phone: "2222"),
        Contact(name: "himanshu",   phone: "2222")
    ]

Here's what I've tried:-

let result = values.filter { value in values.filter({ $0.phone == value.phone }).count > 1 } 
print(result) //this takes lot time to filter 2000+ datas
Lokesh SN
  • 1,583
  • 7
  • 23
sid
  • 33
  • 7
  • let result = values.filter { value in values.filter({ $0. phone == value. phone }).count > 1 } print(result) this takes lot time to filter 2000+ datas – sid Sep 12 '19 at 06:58
  • 3
    Possible duplicate of [Find Duplicate Elements In Array Using Swift](https://stackoverflow.com/questions/29727618/find-duplicate-elements-in-array-using-swift) – Sahil Manchanda Sep 12 '19 at 07:17
  • I don't understand what you are asking: The line "Contact(name: "kedar", phone: "3333")" should be filtered, but how, it is not a duplicate of any other contact in your example. And I think your code is recursive (and therefore needs a lot of time) but this is not necessary. See comment from Sahil Machanda above. – LukeSideWalker Sep 13 '19 at 01:24

1 Answers1

2

Group by phone number, eliminate all phone numbers that are not duplicated, and then filter the original array:

struct Contact {
    let name:String
    let phone:String
}
let contacts = [
    Contact(name: "siddhant", phone: "1234"),
    Contact(name: "nitesh", phone: "1234"),
    Contact(name: "nitin",  phone: "2222"),
    Contact(name: "himanshu", phone: "2222"),
    Contact(name: "kedar", phone: "3333")
]
let singlePhones = Set(Dictionary(grouping: contacts, by: {$0.phone}).filter{$0.1.count == 1}.map{$0.0})
let contacts2 = contacts.filter {!singlePhones.contains($0.phone)}

Result (seems to be what you asked for):

[Contact(name: "siddhant", phone: "1234"),
Contact(name: "nitesh", phone: "1234"), 
Contact(name: "nitin", phone: "2222"), 
Contact(name: "himanshu", phone: "2222")]

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • thank you very much this helped me but can i know how i can get [Contact(name: "siddhant", phone: "1234"), Contact(name: "nitin", phone: "2222")] – sid Sep 12 '19 at 08:13