Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any easy way to merge two arrays in swift along with removing duplicates?

Basically I need a version of appendContentsOf: which does not append duplicate elements.

Example

var a = [1, 2, 3]
let b = [3, 4, 5]

a.mergeElements(b)
//gives a = [1, 2, 3, 4, 5] //order does not matter
like image 671
prad Avatar asked Aug 31 '16 12:08

prad


2 Answers

Simply :

let unique = Array(Set(a + b))
like image 191
Oleg Gordiichuk Avatar answered Sep 18 '22 09:09

Oleg Gordiichuk


Swift 5 Updated

In case you need to combine multiple arrays.

func combine<T>(_ arrays: Array<T>?...) -> Set<T> {
    return arrays.compactMap{$0}.compactMap{Set($0)}.reduce(Set<T>()){$0.union($1)}
}

Usage examples:

1.

    let stringArray1 = ["blue", "red", "green"]
    let stringArray2 = ["white", "blue", "black"]
    
    let combinedStringSet = combine(stringArray1, stringArray2)

    // Result: {"green", "blue", "red", "black", "white"}
    let numericArray1 = [1, 3, 5, 7]
    let numericArray2 = [2, 4, 6, 7, 8]
    let numericArray3 = [2, 9, 6, 10, 8]
    let numericArray4: Array<Int>? = nil
    
    let combinedNumericArray = Array(combine(numericArray1, numericArray2, numericArray3, numericArray4)).sorted()

    // Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
like image 43
Alexey Chekanov Avatar answered Sep 18 '22 09:09

Alexey Chekanov