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.
Asked
Active
Viewed 1.4k times
7
-
possible duplicate of [The best way to remove duplicate values from NSMutableArray in Objective-C?](http://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objective-c) – Cody Gray - on strike Apr 14 '11 at 10:26
-
see this too. i was answered. http://stackoverflow.com/questions/5281295/iphone-sdk-how-to-delete-duplicates-in-the-nsarray/5281491#5281491 – Splendid Apr 14 '11 at 11:39
-
This SO question may help you http://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objective-c – visakh7 Apr 14 '11 at 10:25
-
Does this answer your question? [The best way to remove duplicate values from NSMutableArray in Objective-C?](https://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objective-c) – Cœur Feb 06 '20 at 07:39
6 Answers
18
two liner
NSMutableArray *uniqueArray = [NSMutableArray array];
[uniqueArray addObjectsFromArray:[[NSSet setWithArray:duplicateArray] allObjects]];
3
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. :)

eeerahul
- 1,629
- 4
- 27
- 38

GauravBoss
- 140
- 2
- 4
- 13
-
hi can you tell me can i count no of duplicate element in array1 like 2 is coming in thrice time. – Gajendra Rawat Apr 28 '14 at 08:30
2
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.

deanWombourne
- 38,189
- 13
- 98
- 110
0
NSSet approach is the best if you're not worried about the order of the objects
uniquearray = [[NSSet setWithArray:yourarray] allObjects];

Yogesh Kumar
- 289
- 4
- 4
0
If the order of the values is not important, the easiest way is to create a set from the array:
NSSet *set = [NSSet setWithArray:myArray];
It will only contain unique objects:
If the same object appears more than once in array, it is added only once to the returned set.

Ole Begemann
- 135,006
- 31
- 278
- 256