从数组中删除重复项,比较其对象的属性

时间:2012-11-21 17:56:26

标签: iphone objective-c sorting duplicates duplicate-removal

假设我有一个类Event,它有2个属性:action(NSString)和date(NSDate)。

假设我有一个Event对象数组。问题是“日期”属性可以匹配。

我需要删除重复项,这意味着具有相同日期的2个不同对象是重复的。

我可以删除任何字符串或nsdates数组中的重复项,它们很容易比较。但是如何在复杂对象中进行比较呢?

不要问我到目前为止我做了什么,因为'我脑子里唯一想到的是泡泡排序,但它是一个新手解决方案,而且很慢

非常感谢任何帮助(链接,tuts,代码)。

提前致谢。

修改

感谢dasblinkenlight,我制作了一个自定义方法:

- (NSArray *)removeDuplicatesInArray:(NSArray*)arrayToFilter{

    NSMutableSet *seenDates = [NSMutableSet set];
    NSPredicate *dupDatesPred = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
        YourClass *e = (YourClass*)obj;
        BOOL seen = [seenDates containsObject:e.propertyName];
        if (!seen) {
            [seenDates addObject:e.when];
        }
        return !seen;
    }];
    return [arrayToFilter filteredArrayUsingPredicate:dupDatesPred];
} 

此处 YourClass 是对象所属类的名称, propertyName 是您要访问的对象的属性比较

假设self.arrayWithObjects包含YourClass的对象。

填充后,使用

self.arrayWithObjects = [self removeDuplicatesInArray:self.arrayWithObjects];

你完成了。

所有信用到dasblinkenlight。 干杯!

6 个答案:

答案 0 :(得分:25)

您可以创建NSMutableSet个日期,迭代您的事件列表,并仅添加您之前没有遇到的日期的事件。

NSMutableSet *seenDates = [NSMutableSet set];
NSPredicate *dupDatesPred = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
    Event *e = (Event*)obj;
    BOOL seen = [seenDates containsObject:e.date];
    if (!seen) {
        [seenDates addObject:e.date];
    }
    return !seen;
}];
NSArray *events = ... // This is your array which needs to be filtered
NSArray *filtered = [events filteredArrayUsingPredicate:dupDatesPred];

答案 1 :(得分:3)

这不适用于kvc。我想以下解决方案可以适用于您的情况;

Event *event1 = [[Event alloc] init];
event1.name = @"Event1";
event1.date = [NSDate distantFuture];
Event *event2 = [[Event alloc] init];
event2.name = @"Event2";
event2.date = [NSDate distantPast];
Event *event3 = [[Event alloc] init];
event3.name = @"Event1";
event3.date = [NSDate distantPast];
NSArray *array = @[event1, event2, event3];

NSArray *filteredEvents =  [array valueForKeyPath:@"@distinctUnionOfObjects.name"];

答案 2 :(得分:2)

NSMutableArray *leftObjects = [duplicateArray mutableCopy];
NSMutableArray *nonDuplicates = [NSMutableArray new];
while (leftObjects.count > 0)
{
    YourClass *object = [leftObjects objectAtIndex:0];

    // find all objects matching your comaprison equality definition for YourClass
    NSArray *matches = [leftObjects filteredArrayUsingPredicate:
                        [NSPredicate predicateWithBlock:^BOOL(YourClass *evaluatedObject, NSDictionary *bindings)
                         {
                             return (evaluatedObject.name == object.name);
                         }] ];
    [leftObjects removeObjectsInArray:matches];

    // add first object (arbitrary, may decide which duplicate to pick)
    [nonDuplicates addObject:matches.firstObject];
}

答案 3 :(得分:0)

我认为最有效的方法是使用NSDictionary将对象存储为值,将属性值存储为键,并在将任何对象添加到字典之前检查是否存在,哪个是O(1 )操作,即整个过程将采取O(n)

这是代码

- (NSArray *)removeDuplicatesFromArray:(NSArray *)array onProperty:(NSString *)propertyName {
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

    for (int i=0; i<array.count; i++) {

        NSManagedObject *currentItem = array[i];
        NSString *propertyValue = [currentItem valueForKey:propertyName];

        if ([dictionary valueForKey:propertyValue] == nil) {
            [dictionary setValue:currentItem forKey:propertyValue];
        }
    }

    NSArray *uniqueItems = [dictionary allValues];

    return uniqueItems;
}

您可以将其用作以下

self.arrayWithObjects = [self removeDuplicatesFromArray:self.arrayWithObjects onProperty:@"when"]; 

答案 4 :(得分:0)

这是NSArray类上的Swift扩展,它删除了指定属性的重复项:

extension NSArray {
/**
 - parameter property: the name of the property to check for duplicates

 - returns: an array of objects without objects that share an identical value of the specified property
*/
  func arrayWithoutObjectsOfDuplicateProperty(property : String) -> [AnyObject] {
    var seenInstances = NSMutableSet()

    let predicate = NSPredicate { (obj, bind) -> Bool in
      let seen = seenInstances.containsObject(obj.valueForKey(property)!)

      if !seen {
        seenInstances.addObject(obj.valueForKey(property)!)
      }
        return !seen
      }      
      return self.filteredArrayUsingPredicate(predicate)
  }
}

答案 5 :(得分:0)

这是一个工作的Swift代码剪切,它可以删除重复项,同时保持元素的顺序

// Custom Struct. Can be also class. 
// Need to be `equitable` in order to use `contains` method below
struct CustomStruct : Equatable {
      let name: String
      let lastName : String
    }

// conform to Equatable protocol. feel free to change the logic of "equality"
func ==(lhs: CustomStruct, rhs: CustomStruct) -> Bool {
  return (lhs.name == rhs.name && lhs.lastName == rhs.lastName)
}

let categories = [CustomStruct(name: "name1", lastName: "lastName1"),
                  CustomStruct(name: "name2", lastName: "lastName1"),
                  CustomStruct(name: "name1", lastName: "lastName1")]
print(categories.count) // prints 3

// remove duplicates (and keep initial order of elements)
let uniq1 : [CustomStruct] = categories.reduce([]) { $0.contains($1) ? $0 : $0 + [$1] }
print(uniq1.count) // prints 2 - third element has removed

如果你想知道这种减少魔法是如何工作的 - 这里完全相同,但使用更多扩展的减少语法

let uniq2 : [CustomStruct] = categories.reduce([]) { (result, category) in
  var newResult = result
  if (newResult.contains(category)) {}
  else {
    newResult.append(category)
  }
  return newResult
}
uniq2.count // prints 2 - third element has removed

您只需将此代码复制粘贴到Swift Playground中即可玩游戏。