Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of different (un-common) items of 2 arrays in Swift

Tags:

arrays

ios

swift

This question is similliar to my other one

I have 2 arrays:

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

How can I get the uncommon elements of fruitsArray comparing to vegArray

Expected Output = ["apple", orange]
like image 471
AAA Avatar asked Sep 10 '15 12:09

AAA


People also ask

How do I compare two array elements in Swift?

To check if two arrays are equal in Swift, use Equal To == operator. Equal To operator returns a Boolean value indicating whether two arrays contain the same elements in the same order. If two arrays are equal, then the operator returns true , or else it returns false .

How do you check if an array contains an item Swift?

The contains() method returns: true - if the array contains the specified element. false - if the array doesn't contain the specified element.


1 Answers

Convert arrays to Set and use subtract() function to get what you want

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

   let set1 = Set(fruitsArray)
   let set2 = Set(vegArray)

   let filter = Array(set1.subtract(set2))
   println(filter) //[apple, orange]
like image 55
EI Captain v2.0 Avatar answered Oct 13 '22 21:10

EI Captain v2.0