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

ε祈祈猫儿з 提交于 2019-12-11 04:09:29

问题


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


回答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



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




回答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



来源:https://stackoverflow.com/questions/7229046/compare-two-arrays-and-put-equal-objects-into-a-new-array

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