How do I get unique values from an array

倾然丶 夕夏残阳落幕 提交于 2019-12-04 11:47:20

An simple way is to create an NSSet from the array with duplicates. The result is a set which by definition stores only the unique objects. Then using NSSet's -allObjects method to convert the NSSet back to an NSArray. The only downside is you lose the original ordering by converting to an NSSet.

NSArray *uniqueArray = [[NSSet setWithArray:duplicateArray] allObjects];

If you need to preserve the ordering and can require 10.7+, you can use an NSOrderedSet.

NSArray *uniqueArray = [[NSOrderedSet orderedSetWithArray:duplicateArray] array];

Edit:

Thanks to Mattt Thompson in the WWDC 2013 Session 228 - Hidden Gems in Cocoa and Cocoa Touch, there is another way without creating an intermediate set.

NSArray *uniqueArray = [duplicateArray valueForKeyPath:@"@distinctUnionOfObjects.self"]

You can use the array's valueForKeyPath and set it to distinctUnionOfObjects.self.

NSArray *yearsArray = @[@"1943", @"1945", @"1948", @"1948", @"1948", @"1949"];
NSArray *uniqueYears = [yearsArray valueForKeyPath:@"@distinctUnionOfObjects.self"];
NSLog(@"uniqueYears: %@", uniqueYears);

You provided a NSLog:

unique: (
    (
    1941,
    1942,
    1943,
    1945,
    1948,
    1948,
    1948,
    1949
    ) 
) 

This is not an array of strings. This is an array with one object, which is, itself, an array. That suggests that yearStringArray has that same structure. Clearly your code (and the name of that variable) suggests you thought it should be otherwise.

You should either fix whatever created yearStringArray to actually create an array of strings, or change your code to reflect this structure of yearStringArray, e.g.,

for (yearString in yearStringArray[0]) 
{
    ....
}

Here is bug.

if (![processed containsObject:yearString] == NO)

You have to use

if ([processed containsObject:yearString] == NO)

or

if (![processed containsObject:yearString])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!