Comparing two arrays that ignore order

There NSArrayis a method in the class isEqualToArray:that compares two arrays and indicates whether they match or not.

I have two arrays that have elements in a different order. For instance:

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

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

In the above example, although arr1they arr2have the same elements, isEqualToArray:returns NO. How to compare two arrays, as indicated above, without repeating each element in the for/ loop while?

+5
source share
2 answers

Use NSSetand 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, use:

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

BOOL same=[set1 isEqualToSet:set2];
+7
source

, .

+3

All Articles