0

I made the following method to remove doubles, however it doesn't fully work. Any suggestions?

Thank you for the help,

   -(NSMutableArray*)removeDuplicateCars:(NSMutableArray*)array{
    NSMutableArray *noDuplicates =[[NSMutableArray alloc]init];
    for (int i=0; i<[array count]; i++) {
        int counter =0;
        Car *car =(Car*)[array objectAtIndex:i];
        if ([noDuplicates count]==0) {
            [noDuplicates addObject:car];
        }
        for (int i=0; i<[noDuplicates count]; i++) {
            Car *car2 =(Car*)[array objectAtIndex:i];
            if (![car.name isEqualToString:car2.name]) {
                counter++;
            }
        }
        if (counter==[noDuplicates count]) {
            [noDuplicates addObject:car];
        }
    }
    NSLog(@"number of results = %i",[noDuplicates count]);
    return noDuplicates;
}
William Falcon
  • 9,813
  • 14
  • 67
  • 110

2 Answers2

1

Create an array called "addedCars" - you will use it to store the name of each unique car.

In each iteration, use [NSArray containsObject:] to check if the current name has already been added to "addedCars". If not, add the name to "addedCars" and the car to "noDuplicates". Otherwise, skip this item, as it has already been added to noDuplicates.

Jacek Lampart
  • 1,741
  • 13
  • 25
0

be sure [isEqual:] and [hash] is implemented as you expected

-(NSMutableArray*)removeDuplicateCars:(NSMutableArray*)array{
    NSOrderedSet *set = [[NSOrderedSet alloc] initWithArray:array];
    NSMutableArray *newArr = [NSMutableArray arrayWithCapacity:[set count]];
    for (id obj in set) {
        [newArr addObject:obj];
    }
    return newArr;
}

You used ![car.name isEqualToString:car2.name] to compare objects so I believe you want to filter objects with same name? Than you need to override [isEqual:] for Car

- (BOOL)isEqual:(id)other {
    if ([other isKindOfClass:[self class]]) {
        return [self.name isEuqalToString: [other name]];
    }
    return NO;
}

- (NSUInteger)hash {
    return [self.name hash];
}

also check this question The best way to remove duplicate values from NSMutableArray in Objective-C?

Community
  • 1
  • 1
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143