Reputation: 177
I have an array, as
(John, Jane, John)
I want to get duplicates,as well as original elements of array like
(John,John) I am able to get single occurance from code here
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" but i want all occurences of repeated element like "Name of repeated element-----John,John" .
Upvotes: 0
Views: 104
Reputation: 636
Try this code Using 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];
}
}
Output : john,john,john
Upvotes: 0
Reputation: 8322
Try this Using 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);
Upvotes: 1
Reputation: 6648
I am not sure about your final purpose, the result you want looks meaningless. Anyway, for study purpose, following is an implementation ;)
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);
}
}];
Output: Name of repeated element-----John,John
Upvotes: 0