Find Duplicate Elements In Array Using Swift

后端 未结 12 1412
说谎
说谎 2020-11-29 01:42

How to find Duplicate Elements in Array? I have array of phone numbers so in the phone numbers i should start searching from the right side to the left side and find similar

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 02:15

    To filter an array based on properties, you can use this method:

    extension Array {
    
        func filterDuplicates(@noescape includeElement: (lhs:Element, rhs:Element) -> Bool) -> [Element]{
            var results = [Element]()
    
            forEach { (element) in
                let existingElements = results.filter {
                    return includeElement(lhs: element, rhs: $0)
                }
                if existingElements.count == 0 {
                    results.append(element)
                }
            }
    
            return results
        }
    }
    

    Which you can call as followed, based on the contacts example of Rob:

    let filteredContacts = myContacts.filterDuplicates { $0.name == $1.name && $0.phone == $1.phone }
    

提交回复
热议问题