How can I compare two NSArray
s and put equal objects into a new array?
Asked
Active
Viewed 1.0k times
2

jscs
- 63,694
- 13
- 151
- 195

smartsanja
- 4,413
- 9
- 58
- 106
-
What is the type of the objects in your arrays? You want compare the object's value or just the object(the reference) itself? – EmptyStack Aug 29 '11 at 10:47
-
both arrays contains strings, I want to put common strings to a new array – smartsanja Aug 29 '11 at 10:55
-
Alright. Try this solution. http://stackoverflow.com/questions/7207805/getting-unique-numbers-from-two-arrays/7207883#7207883 – EmptyStack Aug 29 '11 at 10:58
-
@Vijay — you copied your own answer and you link to it. Wouldn't be one enough? – vikingosegundo Aug 29 '11 at 11:17
-
@viking just now i answered for both of them.by read from his comments i realize that he has nsstring in both.so that i have route him to that link.but before that i had thought any object he wants.nothing else – Vijay-Apple-Dev.blogspot.com Aug 29 '11 at 11:21
-
have a look at this: http://stackoverflow.com/questions/6023548/finding-intersection-of-nsmutablearrays/6023588#6023588 same approach as EmptyStack, but gives intersection of the given arrays. – vikingosegundo Aug 29 '11 at 11:22
3 Answers
6
NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",nil];
NSMutableArray *ary_result = [[NSMutableArray alloc] init];
for(int i = 0;i<[array1 count];i++)
{
for(int j= 0;j<[array2 count];j++)
{
if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]])
{
[ary_result addObject:[array1 objectAtIndex:i]];
break;
}
}
}
NSLog(@"%@",ary_result);//it will print a,c

Narayana Rao Routhu
- 6,303
- 27
- 42
2
Answer:
NSArray *firstArr, *secondArr;
// init arrays here
NSMutableArray *intersection = [NSMutableArray array];
for (id firstEl in firstArr)
{
for (id secondEl in secondArr)
{
if (firstEl == secondEl) [intersection addObject:secondEl];
}
}
// intersection contains equal objects
Objects will be compared using method compare:
. If you want to use another method, then just replace if (firstEl == secondEl)
with yourComparator that will return YES to equal objects: if ([firstEl yourComparator:secondEl])

Nekto
- 17,837
- 1
- 55
- 65
-
@narayana, thanks a lot guys, I was able to solve it using if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]] – smartsanja Aug 29 '11 at 11:15
1
//i assume u have first and second array with objects
//NSMutableArray *first = [ [ NSMutableArray alloc]init];
//NSMutableArray *second = [ [ NSMutableArray alloc]init];
NSMutableArray *third = [ [ NSMutableArray alloc]init];
for (id obj in first) {
if ([second containsObject:obj] ) {
[third addObject:obj];
}
}
NSLog(@"third is : %@ \n\n",third);
more over if u have strings in both array then look at this answer of mine

Community
- 1
- 1

Vijay-Apple-Dev.blogspot.com
- 25,682
- 7
- 67
- 76