iOS - Objective-C - Finding Unique Values in an NSArray

Stephen Zaharuk / Tuesday, April 1, 2014

Did you know that the NSArray class has a way of allowing you to easily find any unique values within it. In today's post i'll walk you though how to achieve this.

Lets first assume we have an array of data that looks like this: 

 NSArray* data = @[@"Apples", @"Oranges", @"Grapes", @"Apples", @"Bananas"];

Looking at the array, we can see that value: "Apples" appears twice. So how do we find only the unique values in our array. 

Well, like sorting and filtering, its actually really easy. We'll use Apple's collection operators. Specifically @distinctUnionOfObjects:

NSArray* uniqueValues = [data valueForKeyPath:[NSString stringWithFormat:@"@distinctUnionOfObjects.%@", @"self"]];

The returned array, will only have four objects as opposed to the original array which had 5. 

@[@"Apples", @"Oranges", @"Grapes", @"Bananas"];

Now, this is all great, but in the real world, your array of objects won't necessarily be an array of strings. What if you had an array of custom objects? 

Well, have no fear, b/c it works just as easily. Where as in above we used: "@distinctUnionOfObjects.self", we'll replace the .self with the property path that we want to find the unique values by. 

So, lets assume we had an object called Person. And person has a property called firstName. The call would then look like this:

NSArray* uniqueValues = [data valueForKeyPath:[NSString stringWithFormat:@"@distinctUnionOfObjects.%@", @“firstName”]];

And thats it!

Apple's Collection Operators are really powerful and you can do a lot more than just find unique values. I strongly urge you to read more about them here

Enjoy!

By Stephen Zaharuk (SteveZ)