从 iOS 中的数组中获取重复项和原始项

To Get Duplicate as well as original items from an array in iOS

我有一个数组,因为

(约翰、简、约翰)

我想得到重复项,以及数组的原始元素,例如

(约翰,约翰) 我能够从代码中获得单次出现 这里

NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];

for (id item in set)
{
    NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
    if((unsigned long)[set countForObject:item]>1){
        NSLog(@"of repeated element-----=%@",item);
    }
} 

"Name of repeated element-----John" 但我想要所有出现的重复元素,例如 "Name of repeated element-----John,John" .

我不确定你的最终目的,你想要的结果看起来毫无意义。总之,出于学习目的,下面是一个实现;)

NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];

NSMutableDictionary *countDict = [NSMutableDictionary dictionary];
for (NSString *name in names) {
    if (countDict[name] == nil) {
        countDict[name] = [NSMutableString stringWithString:name];
    }
    else{
        NSMutableString *repeatedName = (NSMutableString *)countDict[name];
        [repeatedName appendString:@","];
        [repeatedName appendString:name];
    }
}
[countDict enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull name, NSString * _Nonnull repeatedNames, BOOL * _Nonnull stop) {
    if (repeatedNames.length > name.length) {
        NSLog(@"Name of repeated element-----%@",repeatedNames);
    }
}];

输出:重复元素的名称-----John,John

试试这个使用 NSPredicate:

NSArray *array = [NSArray arrayWithObjects:@"John", @"Jane", @"John",@"Jane",@"Jane", nil];
NSMutableArray *arrResult = [[NSMutableArray alloc] init];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:array];
for(id name in set)
   {
        if([set countForObject:name] > 1 ){
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", name];
            [arrResult addObjectsFromArray:[array filteredArrayUsingPredicate:predicate]];
        }
    }
    //
    NSLog(@"%@",arrResult);

尝试使用此代码 loop

NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John",@"John", nil];
        NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];
        NSMutableArray *repeatedArray = [[NSMutableArray alloc] init];
        for (id item in set)
        {
            NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
            if((unsigned long)[set countForObject:item]>1){
                NSLog(@"of repeated element-----=%@",item);
                for(int i=0;i<[set countForObject:item];i++)
                 {
                    [repeatedArray addObject:item];
                 }

        }

输出:约翰,约翰,约翰