简体   繁体   中英

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.

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

You can create a generic function that returns the common elements of two arrays by returning the intersection of the two Set s created from the Array s. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM