1

I have two string arrays with unique amounts of content and data in each.

I want to be able to find the count of the number of items that appear in both arrays.

Example:

var array1 = ["Duck", "Dog", "Cat", "Bird", "Elephant", "Cow", "Goat", "Goose"]
var array2 = ["Eagle", "Giraffe", "Cow", "Elephant", "Sheep", "Penguin", "Rhinoceros"]

This should print 2, because Cow and Elephant appear in both array1 and array2.

My progress is below. This is throwing an error: Closure tuple parameter '(offset: Int, element: (String, String))' does not support destructuring with implicit parameters

let compared = zip(array1, array2).enumerated().filter() {
    $1.0.id == $1.1.id
}.count

print(compared)

How do I find the count of items that appear in both arrays? Note, there will never be 3 or more arrays. Always will compare 2 arrays.

Joe
  • 3,772
  • 3
  • 33
  • 64

2 Answers2

8

Maybe you can use Set operation:

var array1 = ["Duck", "Dog", "Cat", "Bird", "Elephant", "Cow", "Goat", "Goose"]
var array2 = ["Eagle", "Giraffe", "Cow", "Elephant", "Sheep", "Penguin", "Rhinoceros"]

print( Set(array1).intersection(array2).count ) //-> 2
OOPer
  • 47,149
  • 6
  • 107
  • 142
  • That was incredibly quick! Works like a charm!! Thank you @OOPer – Joe Apr 16 '18 at 15:38
  • @Joe, please remember, if you want to use other equality check than `==` (for example case-insesitive compare), using `Set` would be a little more difficult thing. – OOPer Apr 16 '18 at 15:42
  • thank you for the heads up. For this comparison, it will always be case-sensitive, so your solution should work just fine. Thanks again! – Joe Apr 16 '18 at 15:45
2

You can create a generic function that returns the common elements of two arrays by returning the intersection of the two Sets created from the Arrays. The Hashable generic type restriction is needed since elements of a Set need to conform to Hashable.

func commonElements<T:Hashable>(between array1:[T],and array2:[T])->[T]{
    return Array(Set(array1).intersection(Set(array2)))
}

commonElements(between: array1, and: array2) // ["Cow", "Elephant"]

If you are only interested in the number of such elements, you can simply call count on the return value.

commonElements(between: array1, and: array2).count // 2
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • Thank you for your more detailed explanation @Dávid, . That information is helpful! – Joe Apr 16 '18 at 15:46