Find Duplicate Elements In Array Using Swift

后端 未结 12 1411
说谎
说谎 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:17

    I've found a way by using reduce, here is the code(Swift 4):

    let testNumbers = [1,1,2,3,4,5,2]
    let nondupicate = testNumbers.reduce(into: [Int]()) {
        if !$0.contains($1) {
            $0.append($1)
        } else {
            print("Found dupicate: \($1)")
        }
    }
    

    As a side effect, it returns an array has no dupicated elements.

    You can easily modify it for counting duplicated elements numbers, checking string arrays etc.

提交回复
热议问题