Sort NSArray of NSStrings based on a super set of ordered Strings

ios, nsarray, nsstring, objective-c, sorting

Solution

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.

Problem

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; }]; ```

Original source