1

I have an array of strings like such:

NSArray *unsortedArray = [NSArray arrayWithObjects:@"MailIn", @"Branch", @"eSign", @"RDC", nil];

I receive this array and it is not gauranteed that all 4 strings will be present. It could have all 4, or only 1.

I need to sort the array in this exact order all the time.. [eSign, RDC, Branch, MailIn]. Keep in mind that there is a chance where one or more of these may not be present. How do I achieve this?? Any help would be greatly appreciated. Thanks in advance!

2 Answers 2

2

If you really want a sort then here is a way to do that. But for only 4 strings I'd likely just unroll @Zev Eisenberg's loop and build it up in code.

NSDictionary* indexes = @{ @"eSign" : @0, @"RDC" : @1, @"Branch" : @2, @"MailIn" : @3 };
NSArray* sorted = [unsorted sortedArrayUsingComparator: ^NSComparisonResult(NSString* s1, NSString* s2) {

    return [indexes[s1] compare: indexes[s2]];
}];
Sign up to request clarification or add additional context in comments.

1 Comment

I like that this is O(n) instead of O(n * m) (or thereabouts), so it will scale better with a larger data set. I would still build the dictionary out of an array, though, so you don't have to type the number for each entry by hand: for (NSUInteger i = 0; i < exemplar.count; i++) { indexes[@(i)] = exemplar[i]; }.
1

I would build a new array, using the exemplar array as a template:

NSArray *exemplarArray = @[ @"eSign", @"RDC", @"Branch", @"MailIn" ];
NSArray *unsorted = @[ @"MailIn", @"Branch", @"eSign", @"RDC" ];

NSMutableArray *sorted = [NSMutableArray array];
for (NSString *string in exemplarArray) {
    if ([unsorted containsObject:string]) {
        [sorted addObject:string];
    }
}
NSLog(@"%@", sorted);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.