5

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 ]
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Pratik Panchal
  • 339
  • 5
  • 13

3 Answers3

3

@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]
Gereon
  • 17,258
  • 4
  • 42
  • 73
2

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]

Daniel
  • 20,420
  • 10
  • 92
  • 149
2

Please check this code, I have used NSArray after getting filtered array you can convert into swift 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)")
Bhupesh
  • 2,310
  • 13
  • 33