Compare two arrays and put equal objects into a new array

10,107

Solution 1

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

Solution 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])

Solution 3

//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

Finding Intersection of NSMutableArrays

Share:
10,107
smartsanja
Author by

smartsanja

Updated on June 05, 2022

Comments

  • smartsanja
    smartsanja almost 2 years

    How can I compare two NSArrays and put equal objects into a new array?

  • smartsanja
    smartsanja over 12 years
    @narayana, thanks a lot guys, I was able to solve it using if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]]