1

I want to compare to mutablearray object condition is below...

array1 = 1,2,3,4; array2 = 2,1,4,3,6,7;

compare this two array object & if the object is already in array then not add otherwise add in array3.

all the array are NSMutable array

please help

1
  • So you are trying to make a third array of the numbers that are not in both arrays? Can you sort the arrays? Commented May 11, 2011 at 12:38

2 Answers 2

1

The easiest way is using sets

NSMutableSet *set = [NSMutableSet setWithArray:array1];
[set addObjectsFromArray:array2];

NSArray *array = [set allObjects];

array will give the merged third array without duplicates.

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

Comments

1
for (int i = 0; i < [array1 count]; i++)
{
    BOOL addThisNumber = YES;
    for (int j = 0; j < [array2 count]; j++)
    {
        int first = [array1 objectAtIndex:i];
        int second = [array2 objectAtIndex:j];
        if ([first compare:second] == NSOrderedSame)
        {
            addThisNumber = NO;
        }
    }

    if (addThisNumber)
    {
        [array3 addObject:first];
    }
}

What I usually do is check for each object in the first array whether or not it occurs in the second array. In the end, add the object if it wasn't found before.

EDIT: Jhaliya's method works much faster then my answer, and using sets like 7KV7's answer is the proper way to use it.

Comments

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.