Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}];
like image 435
Abid Hussain Avatar asked Jan 22 '13 12:01

Abid Hussain


2 Answers

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.

like image 134
Sergey Kalinichenko Avatar answered Nov 06 '22 08:11

Sergey Kalinichenko


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.

like image 3
Benjamin Mayo Avatar answered Nov 06 '22 08:11

Benjamin Mayo