当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - How to get list of common elements of 2 array in swift

问题描述:

I have 2 array:

fruitsArray = ["apple", "mango", "blueberry", "orange"]

vegArray = ["tomato", "potato", "mango", "blueberry"]

How can I get the list of common items in those two array which gives

ouptput = ["mango", "blueberry"]

I cant use if contains(array, string) as I want to compare 2 arrays.

Please help

网友答案:

You don't need a Set (as the comments above have mentioned).

You could instead use a generic function, similar to the one Apple use in their Swift Tour, and thus avoid casting:

func anyCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}

This function can take any two arrays (SequenceTypes) and if any of their elements are the same it returns true.

You could simply modify this generic function to package up an array of strings and return that instead.

For example like this:

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

Usage like this:

var one = ["test2", "dog", "cat"]
var other = ["test2", "cat", "dog"]


var result = arrayOfCommonElements(one,other)

print(result) //prints [test2, dog, cat]

The added benefit here is that this function also works with all same typed arrays. So later if you need to compare two [myCustomObject] arrays, once they both conform to equatable, you're all set! (pun intended)

Edit: (For non common elements) you could do something like this

func arrayOfNonCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> [T.Generator.Element] {

    var returnArray:[T.Generator.Element] = []
    var found = false

    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                found = true
                break
            }
        }

        if (!found){
            returnArray.append(lhsItem)
        }

        found = false
    }
    for rhsItem in rhs {
        for lhsItem in lhs {
            if rhsItem == lhsItem {
                found = true
                break
            }
        }

        if (!found){
            returnArray.append(rhsItem)
        }

        found = false
    }
    return returnArray
}

This implementation is ugly though.

网友答案:

You can also use filter and contains in conjunction:

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

let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 you can even use this
let output = fruitsArray.filter(vegArray.contains)
网友答案:

Convert them to Set and use intersect() function:

let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]
let fruitsSet = Set(fruitsArray)
let vegSet = Set(vegArray)
let output = Array(fruitsSet.intersect(vegSet))
网友答案:

A generic method, inspired by The Swift Programming Language (Swift 3) exercise:

func commonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> [T.Iterator.Element]
    where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
        var common: [T.Iterator.Element] = []

        for lhsItem in lhs {
            for rhsItem in rhs {
                if lhsItem == rhsItem {
                    common.append(lhsItem)
                }
            }
        }
        return common
}
网友答案:

You can even compare the objects inside the array and filter out common array

struct myStruct
    {
      var userid:String;
      var details:String;
      init() {
        userid = "default value";
        details = "default";
      }

    };
    var f1 = myStruct();
    f1.userid = "1";
    f1.details = "Good boy";

    var f2 = myStruct();
    f2.userid = "2";
    f2.details = "Bad boy";

    var f3 = myStruct();
    f3.userid = "3";
    f3.details = "Gentleman";

    var arrNames1:Array = [f1,f3];

    var arrNames2:Array = [f3,f1,f2];

    let filteredArrayStruct =  arrNames1.filter( { (user: myStruct) -> Bool in
      return arrNames2.contains({ (user1: myStruct) -> Bool in
        return user.userid == user1.userid;
      })
    })
print(filteredArrayStruct)
分享给朋友:
您可能感兴趣的文章:
随机阅读: