Sort NSArray from NSStrings based on a super-set of ordered rows

I have an NSArray that contains some NSString objects. For instance:

 NSArray *objects = @[@"Stin",@"Foo",@"Ray",@"Space"]; 

Now I need to sort this array based on the next row order.

 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 the accepted dasblinkenlight answer, I did the 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; }]; 
+6
source share
2 answers

Create an NSComparator that contains a reference to an array of supersets and resolves the relative order of the strings by comparing the results of the call to [superset indexOfObject:str] on both strings. Call sortedArrayUsingComparator: passing in an instance of NSComparator to get the desired order.

+6
source

The dasblinkenlight solution will work, but, like most programming problems, there are several ways to do this. 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]; } }]; 

Variable names correspond to the variable names used in the original question.

This works because the listing is in order. Therefore, what happens is essentially a discard of objects that exist in both arrays in the order specified by sortOrder .

+3
source

All Articles