Finding Intersection of NSMutableArrays

纵然是瞬间 提交于 2019-11-26 08:20:20

问题


I have three NSMutableArray containing names that are added to the lists according to different criterieas.

Here are my arrays pseudocode:

NSMutableArray *array1 = [@\"Jack\", @\"John\", @\"Daniel\", @\"Lisa\"];
NSMutableArray *array2 = [@\"Jack\", @\"Bryan\", @\"Barney\", @\"Lisa\",@\"Penelope\",@\"Angelica\"];
NSMutableArray *array3 = [@\"Jack\", @\"Jerome\", @\"Dan\", @\"Lindsay\", @\"Lisa\"];

I want to find a fourth array which includes the intersection of those three arrays. In this case for example it will be:

NSMutableArray *array4 = [@\"Jack\",@\"Lisa\"];

Because all the three array have jack and lisa as an element. Is there way of simply doing this?


回答1:


Use NSMutableSet:

NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];

The only issue with this is that you lose ordering of elements, but I think (in this case) that that's OK.


As has been pointed out in the comments (thanks, Q80!), iOS 5 and OS X 10.7 added a new class called NSOrderedSet (with a Mutable subclass) that allows you to perform these same intersection operations while still maintaining order.




回答2:


Have a look at this post.

In short: if you can use NSSet instead of NSArray, then it's trivial (NSMutableSet has intersectSet:).

Otherwise, you can build an NSSet from your NSArray and go back to the above case.




回答3:


NSMutableArray *first = [[NSMutableArray alloc] initWithObjects:@"Jack", @"John", @"Daniel", @"Lisa",nil];

NSMutableArray *seconds =[[NSMutableArray alloc] initWithObjects:@"Jack", @"Bryan", @"Barney", @"Lisa",@"Penelope",@"Angelica",nil];

NSMutableArray *third = [ [ NSMutableArray alloc]init];


for (id obj in first) {

    if ([seconds  containsObject:obj] ) {


        [third addObject:obj];

    }


}


NSLog(@"third is : %@ \n\n",third);

OUTPUT:

third is : (

Jack,

Lisa

)




回答4:


This is cleaner than the NSSet approach, and you won't lose the original ordering.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self IN %@ AND self IN %@", array2, array3];
NSArray *array4 = [array1 filteredArrayUsingPredicate:predicate];



回答5:


Here is a working variant from links above

NSPredicate *intersectPredicate = [NSPredicate predicateWithFormat:@"SELF IN %@", @[@500, @400, @600]];
NSArray *intersect = [@[@200, @300, @400] filteredArrayUsingPredicate:intersectPredicate];


来源:https://stackoverflow.com/questions/6023548/finding-intersection-of-nsmutablearrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!