iphoneobjective-ciosiphone-sdk-3.0

compare two arrays and get the common items


I have two arrays, but they have different lengths. I want to compare these two arrays and put common items to a new array. meanwhile there should not be have duplicate items is the third array. I really mess up with this, please give me a help. highly thankful . . .


Solution

  • Something like this?

    NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
    NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
    [set1 intersectSet:set2]; //this will give you only the objects that are in both sets
    
    NSArray* result = [set1 allObjects];
    

    This has the benefit of not looking up the objects in the array, while looping through another array, which has N^2 complexity and may take a while if the arrays are large.

    Edit: set2 doesn't have to be mutable, might as well use just

    NSSet* set2 = [NSSet setWithArray:array2];