有时我们需要删除一个数组中包含另一个数组元素的元素,这时就要获取两个数组中相同的元素了
NSMutableArray *arr1 = [@[@222,@333,@111,@777] mutableCopy];
NSMutableArray *arr2 = [@[@222,@333,@999,@666,@888] mutableCopy];
NSArray *filterArr1 = [arr1 filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF IN %@",arr2]]; //筛选出arr1中arr2有的元素
NSLog(@"arr1有arr2中的:%@",filterArr1);
// 打印
/*
arr1有arr2中的:(
222,
333
)
*/
NSArray *filterArr2 = [arr2 filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF IN %@",arr1]]; //筛选出arr2中arr1有的元素
NSLog(@"arr2有arr1中的:%@",filterArr2);
// 打印
/*
arr2有arr1中的:(
222,
333
)
*/
NSMutableArray *notSameArray = [NSMutableArray new];
[notSameArray addObjectsFromArray:filterArr1];
[notSameArray addObjectsFromArray:filterArr2];
NSLog(@"arr1和arr2的相同元素:%@",notSameArray);
// 打印
/*
arr1和arr2的相同元素:(
222,
333,
222,
333
)
*/
[arr2 removeObjectsInArray:notSameArray];
NSLog(@"删除arr1和arr2的相同元素后的arr2:%@",arr2);
// 打印
/*
删除arr1和arr2的相同元素后的arr2:(
999,
666,
888
)
*/