从数组中删除(不完全)NSDictionaries的副本

时间:2022-02-15 07:38:08

I have an NSMutableArray of many NSDictionaries that contain keys like "Title". In some cases there are duplicates of dictionaries with the same "Title" but differences in the other keys. How can I remove the dictionaries that have the same "Title" key and leave only one in the array?

我有一个NSMutableArray的许多NSDictionaries包含像“标题”这样的键。在某些情况下,存在具有相同“标题”但在其他键中的差异的字典的重复。如何删除具有相同“标题”键并且在数组中只留下一个字典的字典?

Thanks

1 个解决方案

#1


6  

Sort the array using NSSortDescriptor on the key path 'title'. Next, loop over the array and build a new array:

使用关键路径“title”上的NSSortDescriptor对数组进行排序。接下来,遍历数组并构建一个新数组:

NSString *lastTitle = nil;
NSMutableArray *result = [NSMutableArray array];

for (NSDictionary *d in array) {
    NSString *testTitle = [d objectForKey:@"title"];
    if (![testTitle isEqualToString:lastTitle]) {
        [result addObject:d];
        lastTitle = testTitle;
    }
}

Now result contains your filtered list.

现在结果包含您的筛选列表。

It's important to sort the array first for this algorithm to work.

首先对数组进行排序以使该算法起作用非常重要。

#1


6  

Sort the array using NSSortDescriptor on the key path 'title'. Next, loop over the array and build a new array:

使用关键路径“title”上的NSSortDescriptor对数组进行排序。接下来,遍历数组并构建一个新数组:

NSString *lastTitle = nil;
NSMutableArray *result = [NSMutableArray array];

for (NSDictionary *d in array) {
    NSString *testTitle = [d objectForKey:@"title"];
    if (![testTitle isEqualToString:lastTitle]) {
        [result addObject:d];
        lastTitle = testTitle;
    }
}

Now result contains your filtered list.

现在结果包含您的筛选列表。

It's important to sort the array first for this algorithm to work.

首先对数组进行排序以使该算法起作用非常重要。