I have one NSMutableArray which containing duplicates value e.g.[1,2,3,1,1,6]. I want to remove duplicates value and want new array with distinct values.
-
This SO question may help you stackoverflow.com/questions/1025674/…visakh7– visakh72011-04-14 10:25:30 +00:00Commented Apr 14, 2011 at 10:25
-
possible duplicate of The best way to remove duplicate values from NSMutableArray in Objective-C?Cody Gray– Cody Gray ♦2011-04-14 10:26:18 +00:00Commented Apr 14, 2011 at 10:26
-
see this too. i was answered. stackoverflow.com/questions/5281295/…Splendid– Splendid2011-04-14 11:39:34 +00:00Commented Apr 14, 2011 at 11:39
-
Does this answer your question? The best way to remove duplicate values from NSMutableArray in Objective-C?Cœur– Cœur2020-02-06 07:39:24 +00:00Commented Feb 6, 2020 at 7:39
Add a comment
|
6 Answers
two liner
NSMutableArray *uniqueArray = [NSMutableArray array];
[uniqueArray addObjectsFromArray:[[NSSet setWithArray:duplicateArray] allObjects]];
1 Comment
Cœur
And use
NSOrderedSet if you want the original order.My solution:
array1=[NSMutableArray arrayWithObjects:@"1",@"2",@"2",@"3",@"3",@"3",@"2",@"5",@"6",@"6",nil];
array2=[[NSMutableArray alloc]init];
for (id obj in array1)
{
if (![array2 containsObject:obj])
{
[array2 addObject: obj];
}
}
NSLog(@"new array is %@",array2);
The output is: 1,2,3,5,6..... Hope it's help you. :)
1 Comment
Gajendra Rawat
hi can you tell me can i count no of duplicate element in array1 like 2 is coming in thrice time.
I've made a category on NSArray with this method in :
- (NSArray *)arrayWithUniqueObjects {
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[self count]];
for (id item in self)
if (NO == [newArray containsObject:item])
[newArray addObject:item];
return [NSArray arrayWithArray:newArray];
}
However, this is brute force and not very efficient, there's probably a better approach.