0

Array1 = [Washington, Franklin, Florida, Alaska, California, Georgia]

Array2 = [California, Washington, Georgia]

I want to get

Array1 = [Washington, California, Georgia]

4 Answers 4

3
var array1 = ["Washington", "Franklin", "Florida", "Alaska", "California", "Georgia"]
var array2 = ["California", "Washington", "Georgia"]

let filterArray = array1.filter {
    array2.contains($0)
}

The filterArray is what you want

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

Comments

2

You can use filter for achieving desired output

Using filter:

let array1 = ["Washington", "Franklin", "Florida", "Alaska", "California", "Georgia"]
let array2 = ["California", "Washington", "Georgia"]

let aryCommonElements = array1.filter { array2.contains($0)}

Output:

["Washington", "California", "Georgia"]

Hope this will help you :)

2 Comments

He can not use the sets , because he wants to maintain the order
I have showed two methods. One with set and other with Filter. The filter one will work. I have edited my answer please check it
2

try this

let filteredArray = array1.filter({Array2.contains($0)})

Comments

1

If you want to retrieve only common elements than use:

In Swift 3

let Array1 = ["Washington", "Franklin", "Florida", "Alaska", "California", "Georgia"]

let Array2 = ["California", "Washington", "Georgia"]

let common = GetCommonElements(lhs: Array1, rhs: Array2)

print(common)

func GetCommonElements <T, U> (lhs: T, rhs: U) -> [T.Iterator.Element] where T: Sequence, U: Sequence, T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
       var returnArray:[T.Iterator.Element] = []
       for lhsItem in lhs {
           for rhsItem in rhs {
               if lhsItem == rhsItem {
                  returnArray.append(lhsItem)
               }
           }
       }
       return returnArray
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.