12

How can I compare two arrays in swift which have a common element and get that element?

let a1 = [1, 2, 3]
let a2 = [4, 2, 5]

I want to compare a1 and a2 and get result 2 from comparison in swift 2.2. How?

Istiak Morsalin
  • 10,621
  • 9
  • 33
  • 65
  • 3
    http://stackoverflow.com/questions/25714985/how-to-determine-if-one-array-contains-all-elements-of-another-array-in-swift – Bhavin Bhadani Dec 28 '16 at 05:32
  • Check it http://stackoverflow.com/questions/32439289/how-to-get-list-of-common-elements-of-2-array-in-swift?rq=1 – Amanpreet Dec 28 '16 at 05:33

2 Answers2

23

You can use filter function of swift

let a1 = [1, 2, 3]
let a2 = [4, 2, 5]

let a = a1.filter () { a2.contains($0) }

print(a)

print : [2]

if data is

let a1 = [1, 2, 3]
let a2 = [4, 2, 3, 5]

print : [2, 3]

If you want result in Int not in array

let result = a.first

You get optional Int(Int?) with result of first common element

ERbittuu
  • 968
  • 8
  • 19
4

Another alternative would to use Sets:

let a1 = [1, 2, 3]
let a2 = [4, 2, 5]

let a = Set(a1).intersection(Set(a2)) // <- getting the element itself
print(a) // 2

let contains: Bool = !Set(a1).isDisjoint(with: Set(a2)) // <- checking if they have any common element
print(contains) // true
Vitalii
  • 4,267
  • 1
  • 40
  • 45