Joe
Joe

Reputation: 3961

How do you compare two arrays to get the count of similar objects?

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.

Upvotes: 1

Views: 1168

Answers (2)

David Pasztor
David Pasztor

Reputation: 54745

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

Upvotes: 2

OOPer
OOPer

Reputation: 47896

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

Upvotes: 8

Related Questions