-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
3
  • let result = values.filter { value in values.filter({ $0. phone == value. phone }).count > 1 } print(result) this takes lot time to filter 2000+ datas Commented Sep 12, 2019 at 6:58
  • 3
    Possible duplicate of Find Duplicate Elements In Array Using Swift Commented Sep 12, 2019 at 7: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. Commented Sep 13, 2019 at 1:24

1 Answer 1

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")]

Sign up to request clarification or add additional context in comments.

1 Comment

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")]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.