I have an NSArray
which contains some NSString
objects. For example:
NSArray *objects = @[@"Stin",@"Foo",@"Ray",@"Space"];
Now I need to sort this array based on following order of Strings.
NSArray *sortOrder = @[@"John",@"Foo",@"Space",@"Star",@"Ray",@"Stin"];
So the answer should be
NSArray *sorted = @[@"Foo",@"Space",@"Ray",@"Stin"];
How can I achieve this?
ANSWER: Based on Accepted answer of dasblinkenlight, I did following and it worked to charm.
NSMutableArray *objects = @[@"Star",@"Stin",@"Foo",@"Ray",@"Space",@"John"];
NSArray *sortOrder = @[@"John",@"Foo",@"Space",@"Star",@"Ray",@"Stin"];
[objects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int index1 = [sortOrder indexOfObject:obj1];
int index2 = [sortOrder indexOfObject:obj2];
if (index1 > index2)
return NSOrderedDescending;
if (index1 < index2)
return NSOrderedAscending;
return NSOrderedSame;
}];
Create NSComparator
that holds a reference to the superset array, and decides the relative order of strings by comparing the results of calling [superset indexOfObject:str]
on both strings. Call sortedArrayUsingComparator:
passing an instance of NSComparator
to get the desired ordering.
dasblinkenlight's solution would work, but like most programming problems there are multiple ways to go about it. Here is one such alternative:
NSMutableArray *sorted = [NSMutableArray arrayWithCapacity:0];
[sortOrder enumerateObjectsUsingBlock:^(NSString *sortedString, NSUInteger idx, BOOL *stop) {
if ([objects containsObject:sortedString]) {
[sorted addObject:sortedString];
}
}];
The variable names correspond to the variable names used in the original question.
This works because the enumeration happens in order. Therefore, what takes place is, essentially, a cull of the objects that exist in both arrays in the order as specified by sortOrder
.
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