cannyboy
cannyboy

Reputation: 24416

How to tell how may unique elements there are an NSArray

I've got an array (actually a mutable array) of NSStrings, and I want to find out how many unique elements the are in the array.

For instance, say the array is made up of:

Orange, Lemon, Lemon, Orange, Lemon

Then there are just two unique elements (Orange and Lemon). And this array:

Paul, Steve, John, Harry, Paul, John

..has four unique unique elements.

How do I discover this number?

Upvotes: 1

Views: 461

Answers (3)

Lucien
Lucien

Reputation: 8393

NSUInteger count = [[array valueForKeyPath:@"@distinctUnionOfObjects.self"] count];

Upvotes: 0

Massimo Cafaro
Massimo Cafaro

Reputation: 25419

Do a linear scan of the array, and, for each element, add it to an NSMutableSet. Finally count the number of elements in the NSMutableSet. The NSMutableSet will not allow adding a repeated element.

This is faster then sorting the array, and then doing a linear scan incrementing a variable each time you discover a new element.

EDIT: the implementation in Objective-C has been provided by JoostK.

Upvotes: 1

Joost
Joost

Reputation: 10413

NSSet can't contain equal objects, so the following works:

NSUInteger count = [[NSSet setWithArray:array] count];

Upvotes: 13

Related Questions