开发者

Compare two arrays and put equal objects into a new array [duplicate]

开发者 https://www.devze.com 2023-04-01 14:06 出处:网络
This question already has answers here: Finding Intersection of NSMutableArrays (5 answers) Closed 8 years ago.
This question already has answers here: Finding Intersection of NSMutableArrays (5 answers) Closed 8 years ago.

How can I compare two NSArrays 开发者_开发百科and put equal objects into a new array?


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消