Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two NSArrays and return number of differences

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"

like image 352
Matt S. Avatar asked May 30 '10 16:05

Matt S.


1 Answers

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.

like image 193
Laurent Etiemble Avatar answered Sep 23 '22 01:09

Laurent Etiemble