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?
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];
I suggest you sort both arrays, and compare the results with the method you've tried.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With