Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two arrays ignoring order [duplicate]

In the class NSArray, there's a method isEqualToArray: which compares two arrays and indicates whether they match or not.

I've two arrays which have elements in different order. For example:

NSMutableArray* arr1 = [@[@"one", @"two", @"three"] mutableCopy];
NSMutableArray* arr2 = [@[@"three", @"one", @"two"] mutableCopy];

BOOL same = [arr1 isEqualToArray:arr2];
NSLog(@"%d", same);

In above example, even though arr1 and arr2 have same the elements, isEqualToArray: is returning NO. How can I compare two arrays as mentioned above without iterating through each element in a for/while loop?

like image 358
Satyam Avatar asked Mar 31 '13 17:03

Satyam


2 Answers

Use NSSet and then compare.

NSSet *set1=[NSSet setWithArray:arr1];
NSSet *set2=[NSSet setWithArray:arr2];

BOOL same=[set1 isEqualToSet:set2];

EDIT:

If you have duplicates in arr1 and arr2, then use :

NSCountedSet *set1=[NSCountedSet setWithArray:arr1];
NSCountedSet *set2=[NSCountedSet setWithArray:arr2];

BOOL same=[set1 isEqualToSet:set2];
like image 63
Anoop Vaidya Avatar answered Sep 24 '22 01:09

Anoop Vaidya


I suggest you sort both arrays, and compare the results with the method you've tried.

like image 25
Levi Avatar answered Sep 20 '22 01:09

Levi