Is it possible to remove duplicate values ​​from an array with nil values

An array can be any type of type

let myArray1 = [ 1, 2, 3, 1, 2, 1, 3, nil, 1, nil]

let myArray2 = [ 1, 2.0, 1, 3, 1.0, nil]

After removing duplicate values from the array, the new array should be:

Conclusion -

 [ 1, 2, 3, nil ]
+4
source share
3 answers

@ Daniel's solution as a general feature:

func uniqueElements<T: Equatable>(of array: [T?]) -> [T?] {
    return array.reduce([T?]()) { (result, item) -> [T?] in
        if result.contains(where: {$0 == item}) {
            return result
        }
        return result + [item]
    }
}

let array = [1,2,3,1,2,1,3,nil,1,nil]

let r = uniqueElements(of: array) // [1,2,3,nil]
+3
source

You can use this shortcut to remove duplicate entries:

myArray.reduce([Int?]()) { (result, item) -> [Int?] in
    if result.contains(where: {$0 == item}) {
        return result
    }
    return result + [item]
}

conclusion: [1, 2, 3, nil]

+2
source

Please check this code, I used NSArray after receiving a filter that you can convert to a fast array

    let arr = [1, 1, 1, 2, 2, 3, 4, 5, 6, nil, nil, 8]

    let filterSet = NSSet(array: arr as NSArray as! [NSObject])
    let filterArray = filterSet.allObjects as NSArray  //NSArray
    print("Filter Array:\(filterArray)")
+2
source

Source: https://habr.com/ru/post/1692299/


All Articles