0

How can an array of objects be sorted by comparing one of their properties (NSString *) to objects (already sorted) in another array of (NSString *)s?

I fill an array of e.g. Person objects in the order a number of threads happen to complete in. I would then like to compare each Person.name against an array of name objects that is already ordered. The result would be the Person array sorted in the same order as the names array by the person.name property.

2
  • Do you have a code example or atleast an example of some input and expected output? Commented Nov 14, 2012 at 20:05
  • Updated question thanks. Is there a sort descriptor for this rather than writing a custom solution? Commented Nov 14, 2012 at 20:09

2 Answers 2

1

You could try something similar to this, with very little details this the best I could come up with:

NSArray *array1 = [NSArray array];
NSArray *sortedArray = [NSArray array];
NSMutableArray *tmpArray = [NSMutableArray array];

for (id object in sortedArray)
{
    if ([array1 containsObject:object])
        [tmpArray addObject:object];
}

This code loops threw the sorted array and checks if the unsorted array contains that same object. If it does it placed it in tmpArray. When if finishes it will have a sorted array with the items it contained.

Here's a link I found using NSPredicate for a more optimized solution https://stackoverflow.com/a/2873439/507299.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, yeah I thought of this, but wondered if there was a more optimized solution using a sort descriptor.
There are NSPredicate that shorten the code let me see if I can find a example for you.
0

Maybe something like that

NSMutableArray *excluded = [NSMutableArray array];
NSArray *sortedNames = @[@"name1", @"name5", @"name3", /*more names*/ @"nameX"];
NSArray *tmp = [inputArray sortedArrayUsingComparator: ^(id p1, id p2) {

    NSUInteger pos1 = [sortedNames indexOfObject:((Person *)p1).name];
    NSUInteger pos2 = [sortedNames indexOfObject:((Person *)p2).name];

    if (pos1 == NSNotFound && ![excluded containsObject:p1]) {
        [excluded addObject:p1];
    }
    if (pos2 == NSNotFound && ![excluded containsObject:p2]) {
        [excluded addObject:p2];
    }

    if (pos1 == pos2) return NSOrderedSame;
    if (pos1 > pos2) return NSOrderedDescending;
    return NSOrderedAscending;
}];
NSArray *sortedArray = [tmp subarrayWithRange:NSMakeRange(0, [tmp count] - [excluded count])];

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.