对两数组求取相同和不同元素
举三个例子:
一.遍历两数组,得到相同和不同元素
NSArray* arr2 =@[@4,@3,@2,@1];
NSArray* arr1 =@[@2,@3,@4,@5];
__block NSMutableArray *sameObject = [NSMutableArray arrayWithCapacity:5];
[arr2enumerateObjectsUsingBlock:^(id _Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
NSNumber*number1 = obj;
[arr1enumerateObjectsUsingBlock:^(id _Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
if([number1isEqual:obj]) {
[sameObjectaddObject:number1];
*stop =YES;
}
}];
}];
NSLog(@"same:%@",sameObject);
__block NSMutableArray *difObject = [NSMutableArray arrayWithCapacity:5];
//找到arr2中有,arr1中没有的数据
[arr2enumerateObjectsUsingBlock:^(id _Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
NSNumber *number1 = obj;//[obj objectAtIndex:idx];
__blockBOOLisHave =NO;
[arr1enumerateObjectsUsingBlock:^(id _Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
if([number1isEqual:obj]) {
isHave =YES;
*stop =YES;
}
}];
if(!isHave) {
[difObjectaddObject:obj];
}
}];
//找到arr1中有,arr2中没有的数据
[arr1enumerateObjectsUsingBlock:^(id _Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
NSNumber *number1 = obj;//[obj objectAtIndex:idx];
__blockBOOLisHave =NO;
[arr2enumerateObjectsUsingBlock:^(id _Nonnullobj,NSUIntegeridx,BOOL*_Nonnullstop) {
if([number1isEqual:obj]) {
isHave =YES;
*stop =YES;
}
}];
if(!isHave) {
[difObjectaddObject:obj];
}
}];
NSLog(@"diff:%@",difObject);
二.利用集合set的特性
NSArray*arr2 =@[@4,@3,@2,@1];
NSArray*arr1 =@[@2,@3,@4,@5];
NSMutableSet *set1 = [NSMutableSet setWithArray:arr1];
NSMutableSet *set2 = [NSMutableSet setWithArray:arr2];
[set1intersectSet:set2];
NSLog(@"same:%@",set1);
{
NSMutableSet *set1 = [NSMutableSet setWithArray:arr1];
NSMutableSet *set2 = [NSMutableSet setWithArray:arr2];
[set2minusSet:set1];
NSMutableSet *set3 = [NSMutableSet setWithArray:arr2];
[set1minusSet:set3];
[set2unionSet:set1];
NSLog(@"diff:%@",set2);
}
三.使用正则
NSArray* arr2 =@[@4,@3,@2,@1];
NSArray* arr1 =@[@2,@3,@4,@5];
NSPredicate * filterPredicate_same = [NSPredicate predicateWithFormat:@"SELF IN %@",arr1];
NSArray* filter_no = [arr2filteredArrayUsingPredicate:filterPredicate_same];
NSLog(@"same:%@",filter_no);
//找到在arr2中不在数组arr1中的数据
NSPredicate * filterPredicate1 = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",arr1];
NSArray* filter1 = [arr2filteredArrayUsingPredicate:filterPredicate1];
//找到在arr1中不在数组arr2中的数据
NSPredicate * filterPredicate2 = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",arr2];
NSArray* filter2 = [arr1filteredArrayUsingPredicate:filterPredicate2];
//拼接数组
NSMutableArray *array = [NSMutableArray arrayWithArray:filter1];
[arrayaddObjectsFromArray:filter2];
NSLog(@"diff:%@",array);
demo 链接:https://github.com/licl19/sameAndDifferentInArray.git