Compare 2 nsmutablearray and get different object to third array in ios

可紊 提交于 2019-12-01 02:17:38

问题


I want to compare 2 NSMutableArray and get different object into third Array. How can i do that ?

Array1 can loop object .

Array1 = "a", "b","c","d","a","b","c";
Array2 = "a", "b", "c";

And then result

Array3 = "d";

Thanks in advance


回答1:


Use sets for set operations:

NSSet *set1 = [NSSet setWithArray:array1];
NSMutableSet *set2 = [NSMutableSet setWithArray:array2];
[set2 minusSet:set1];



回答2:


You Can try this too.

NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"1", nil];
NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:@"2",@"1", nil];    

NSMutableArray *largeArray;
NSMutableArray *shortArray;
if([array1 count] > [array2 count]){
    largeArray = array1;
    shortArray = array2; 
} else {
    largeArray = array2;
    shortArray = array1; 
}
[largeArray removeObjectsInArray:shortArray];

for (NSString *va in largeArray) {
    NSLog(@"%@",va);
}



回答3:


NSMutableArray *gotDiffArry= [[NSMutableArray alloc] init];
for(int i = 0 ; i < FirstArray.count; i++) {
    if(i < seconArray.count){
        if(![seconArray[i] isEqual:firstArray[i]]){
             [gotDiffArry addObject:[NSNumber numberWithInt:i]];
         }
    } else {
        [gotDiffArry addObject:[NSNumber numberWithInt:i]];
    }
}

EDITED:

for (int i = 0 ; i < firstArray.count ; i ++)
{

 NSString *search = [firstArray objectAtIndex:i];
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF CONTAINS %@", search];
 NSMutableArray *temAraay = [secondArray filteredArrayUsingPredicate: predicate];
 if(temArray.count >=0 )
 {
   NSLog("%@", [temArray objectAtIndex:0]); 
 }
}



回答4:


I have used the following and got the desired results:

for(int i =0; i<[arraytwo count]; i++)
{
    if (![arrayone containsObject:[arraytwo objectAtIndex:i]])
        [arraythree addObject: [arraytwo obectAtIndex:i]];
}    
NSLog(@"%@",arraythree);


来源:https://stackoverflow.com/questions/17611616/compare-2-nsmutablearray-and-get-different-object-to-third-array-in-ios

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