Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check there's duplicate value in array or not?

var arrEmails = NSMutableArray()
arrEmails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]

above is my Array and i want to check is there any duplicate value or not. and for that i write below code.

let set = NSCountedSet.init(array: arrEmails as! [Any])
        var duplicates: Int = 0

        for var object in set {
            if set.count(for: object) > 1 {
                duplicates = duplicates+1
            }
        }

but in above code, if array contains values like below than it returns me duplicates value 1.

arrEmails = ["[email protected]", "", "", "[email protected]", "", ""]

I don't want to remove duplicate value, i just want to check number of duplicate value in array. How can check? please help me out.

like image 626
Pankil Avatar asked Oct 21 '25 12:10

Pankil


1 Answers

First of all stop using NSMutableArray and use Swift array.

So you have this array

let emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]

Now you can check whether there are duplicates simply writing

let hasDuplicates = emails.count != Set(emails).count

Note, this does work only if the generic type of the array is Hashable.

like image 97
Luca Angeletti Avatar answered Oct 23 '25 04:10

Luca Angeletti