how to intersect two arrays in objective C?
Asked Answered
J

1

22

I have two arrays . Array1 contains 15 objects and Array2 contains 4 objects. There are 2 common objects from both array, I just want to get that resulted array of that 2 objects.

It should be like intersection of two Set, but how to do in Objective C for array..? Please help. thanks.

Jardine answered 29/8, 2012 at 8:39 Comment(3)
What about creating 2 sets with your arrays and then invoking the intersection over the sets?Striped
see this https://mcmap.net/q/183124/-comparing-two-arraysBarbecue
Thanks @Hadley and Ricard, I got the solution of filtering my result using NSSet. Got my resulted array ..!!Jardine
N
56

Using NSMutableSet

NSMutableSet *set1 = [NSMutableSet setWithArray: array1];
NSSet *set2 = [NSSet setWithArray: array2];
[set1 intersectSet: set2];
NSArray *resultArray = [set1 allObjects];
Nilgai answered 29/8, 2012 at 8:50 Comment(4)
Here set1 should be NSMutableSet because NSMutableSet has extension intersectSet methodShavonneshaw
how well does this work if these arrays are pretty big, like 2000 objects each? Is this a scalable solution?Igenia
It's worth saying why one would use NSSet for efficiency reasons! The code using NSSets will perform faster (better runtime efficiency) than the for loop equivelant.Eliason
@Akhrameev I'm rejecting your edit suggestion as in any place is being asked to order the set. Feel free to add your suggestion as a new answerNilgai

© 2022 - 2024 — McMap. All rights reserved.