Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to remove duplicate values from Array with nil values

Tags:

arrays

swift

Array can be any type like

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:

Output -

 [ 1, 2, 3, nil ]
like image 693
Pratik Panchal Avatar asked Jan 17 '18 09:01

Pratik Panchal


2 Answers

@Daniel's solution as a generic function:

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]
like image 86
Gereon Avatar answered Oct 10 '22 07:10

Gereon


You can use this reduce to remove duplicated entries:

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

output: [1, 2, 3, nil]

like image 35
Daniel Avatar answered Oct 10 '22 07:10

Daniel