I have 2 Nsarray where objects of 2 arrays are same may be indexes of the object differs, but it should print both are equal irrespective of there indexes
NSArray *arr1 = [[NSArray alloc]initWithObjects:@"aa", @"bb", @"1", @"cc", nil];
NSArray *arr2 = [[NSArray alloc]initWithObjects:@"bb", @"cc", @"1", @"aa", nil];
if ([arr1 isEqualToArray:arr2])
{
NSLog(@"Equal");
}
else
{
NSLog(@"Not equal");
}
the above code is printing 'Not equal' but it should print 'Equal'. How can I do this?
Try this. What I am doing is make a copy of your first array & remove copy elements from the second array. If its empty then its equal, else not equal.
This has lesser memory foot print than @rmaddy solution. You create a duplicate of only one array not both arrays...
UPDATE1: If you want to use
arr2
after this then its been changed. You need to make a copy of it, then in that case memory-wise its same as what rmaddy solution takes. But still this solution is superior since,NSSet
creation time is far more thanNSArray
- source.UPDATE2: Updated to make the answer more comprehensive incase one array is bigger than other.
Another option is to convert the NSArrays to JSON strings, and compare using isEqualToString.
I'd be curious as to a performance comparison of all these methods.
Those two arrays are not equal. Two arrays are equal is they both have the same objects in the same order.
If you want to compare with no regard to order then you need to use two
NSSet
objects.Most of the answers here actually do not work for fairly common cases (see their comments). There is a very good data structure that will solve this problem: NSCountedSet.
The counted set is unordered, but does care about the number of items present, so you don't end up with
@[1, @1, @2] == @[@1, @2, @2]
.I found the solution,,we can achieve that by sorting the array elements