How to remove duplicate values from array
13,932
Solution 1
two liner
NSMutableArray *uniqueArray = [NSMutableArray array];
[uniqueArray addObjectsFromArray:[[NSSet setWithArray:duplicateArray] allObjects]];
Solution 2
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. :)
Solution 3
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.
Author by
neel
Updated on June 04, 2022Comments
-
neel almost 2 years
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.
-
Gajendra Rawat about 10 yearshi can you tell me can i count no of duplicate element in array1 like 2 is coming in thrice time.
-
Cœur over 4 yearsAnd use
NSOrderedSet
if you want the original order.