Search Your Question

How to take common elements from two array in ios?

Ans. 

Swift higher order function is very useful. See below example.


let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

// only Swift 1
let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 and above
let output = fruitsArray.filter{ vegArray.contains($0) }
// or
let output = fruitsArray.filter(vegArray.contains)


Array vs Set

let array1: Array = ...
let array2: Array = ...

// Array
let commonElements = array1.filter(array2.contains)

// vs Set
let commonElements = Array(Set(array1).intersection(Set(array2)))

// or (performance wise equivalent)

let commonElements: Array = Set(array1).filter(Set(array2).contains)

Another way in Swift 4.0

   var someHash: [String: Bool] = [:]

   fruitsArray.forEach { someHash[$0] = true }

   var commonItems = [String]()

   vegArray.forEach { veg in
    if someHash[veg] ?? false {
        commonItems.append(veg)
    }
   }


   print(commonItems)



No comments:

Post a Comment

Thanks