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?

2

2 Answers 2

24

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

Sign up to request clarification or add additional context in comments.

7 Comments

Yes, It is work for all array. condition is only both array are same type. Here is [Int] array
How can i get a not in array but simple Int?
@JasonBourne Is your arrays have only one common object?
Lets say it has one common object
You should use a Set to speed up the .contains() call.
|
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.