Get duplicates in NSArray

I have an NSArray that contains multiple repeating objects. I want to print which objects are duplicated, for example:

NSArray * array = [NSArray arrayWithObjects: A, B, C, A, B]; 

Now I want to print on console A and B as they are duplicated.

How can I do it?

+4
source share
5 answers

Use an NSCountedSet and print only those elements that return the number> 1 method for countForObject:

+5
source

You can use NSCountedSet for this. you can add all objects to the counted set, and then use the countForObject : method to find out how often each object appears. read about NSCountedSet for further reference

+10
source

This is probably far from ideal, but it works

 NSArray *array = [NSArray arrayWithObjects:@"a", @"b", @"b", @"v", @"f", @"f", nil]; NSMutableArray *un_array = [NSMutableArray array]; NSMutableArray *dupArray = [NSMutableArray array]; for (id obj in array) { if (![un_array containsObject:obj]) [un_array addObject:obj]; else [dupArray addObject:obj]; } NSLog(@"DUPLICATES:"); for (id obj in dupArray) NSLog(@"%@", [obj description]); 
+2
source

Another approach is to sort the array and find adjacent duplicates. Probably a bit slower than using a hashed set, but the same basic “big O”.

0
source

Try my logic:

 for(int i=0; i < array.count; i++) { for(int j=0; j< i; j++) { if([[array objectAtIndex:i] isEqualToString:[array objectAtIndex:j]] ) { NSLog(@"%@",[array objectAtIndex:i]); } } } 
-1
source

All Articles