Take the 2-minute tour ×

How can I take two NSArrays, compare them, then return the number of differences, preferably the number of different objects, for example:

Array 1: one two three

Array 2: two four one

I would like that to return "1"

share|improve this question
Why is that one difference and not two? –  Carl Norum May 30 '10 at 16:28
because there's one element that's different. 1 has "three" and 2 has "four" –  Matt S. May 30 '10 at 16:33

2 Answers 2

up vote 17 down vote accepted

You can do this by using an intermediate NSMutableArray:

NSArray *array1 = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"Two", @"Four", @"One", nil];
NSMutableArray *intermediate = [NSMutableArray arrayWithArray:array1];
[intermediate removeObjectsInArray:array2];
NSUInteger difference = [intermediate count];

With that way, only common elements will be removed.

share|improve this answer
Works perfectly! Thanks a bunch! –  Matt S. May 30 '10 at 16:38
If you have a relatively large # of items in the array this might be slow. Maybe. Measure it. If it is, considering using NSSet instead. –  bbum May 30 '10 at 18:39

I found that the answer above didn't take arrays of differing size into account. If you do it as above, you should check to see which array.count is smaller and

[largerArray removeObjectsInArray:shorterArray];


I made them both NSSets and then compared.

[set1 isEqualToSet:set2];

That way size and order are both dealt with properly! (I didn't need to know the number of differences)

share|improve this answer

Your Answer


