1

I have an NSArray containing objects with a size property.

How can I check if the NSArray has two objects with the same value for size?

Can I do something like:

int i = 0;
for (id item1 in myArray) {
    NSDecimalNumber *size1 = [item1 size];

    for (id item2 in myArray) {
        NSDecimalNumber *size2 = [item2 size];

        if ([size1 isEqual:size2]) {
            i ++;
        }
    }
}

if (i > [myArray count]) {
    NSLog(@"Duplicate Sizes Exist");
}

Or is there an easier way?

1
  • You can do the above, but it's "N-squared" and generally considered poor form for larger collections. Commented May 9, 2013 at 11:26

4 Answers 4

3

Try this code:

NSSet *myset = [NSSet setWithArray:[myarray valueForKey:@"size"]];
int duplicatesCount = [myarray count] - [myset count];

size here is the object property.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use KVC collection operators: [myArray valueForKeyPath:@"@distinctUnionOfObjects.size"]. More details here: nshipster.com/kvc-collection-operators
1

Use NSCountedSet. then add all your objects to the counted set, and use the countForObject: method to find out how often each object appears in your array.

You can check this link also how-to-find-duplicate-values-in-arrays

Hope it helps you

1 Comment

Yeah, but the objects may be different but have the same size. So the array my have 2 objects which are size 3, but one is brown and one is grey. Your suggestion would only pick up identical objects.
0

Probably simplest is to sort the array based on the size field and then step through the sorted list looking for adjacent dupes.

You could also "wrap" each object in one that exports the size as its key and use a set. But that's a lot of extra allocations.

But if you only want to know if dupes exist, and not which ones they are, create an NSNumber for each object's size and insert the NSNumbers in a set. The final size will tell you how many dupes.

1 Comment

That's a good suggestion as the array is already sorted. Thanks Hot Licks :)
0
NSArray *cleanedArray = [[NSSet setWithArray:yourArraywithDuplicatesObjects ] allObjects];

Use Sets this will remove all duplicates objects.Will return NSArrayNSCountedSet and use countForObject: method to find out how often each object appears how many times.

1 Comment

I knew there would be a lot of suggestions to use NSSet, but I don't have duplicate objects, just need to check if any objects have the same propert value :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.