1

I have an array like this:

NSArray *needSortedArray = @[@"Alex", @"Rachel", @"Mohamad"];

and an array of index like this:

NSArray *indexArray = @[@1, @0, @2];

So the output I want will look like this:

needSortedArray = @[@"Rachel", @"Alex", @"Mohamad"];

How can I do this? Is it possible?

2 Answers 2

5

Try this:

    NSArray *unsortedArray = @[@"Alex", @"Rachel", @"Mohamad"];
    NSArray *indexArray = @[@1, @0, @2];

    NSMutableArray * sortedArray = [[NSMutableArray alloc] initWithCapacity:unsortedArray.count];
    for (NSNumber * num in indexArray)
    {
        [sortedArray addObject:[unsortedArray objectAtIndex:num.integerValue]];
    }

   //now sortedArray has sorted objects.
Sign up to request clarification or add additional context in comments.

1 Comment

Good solution if indexes are not equal and in correct indexes range for unsortedArray.
0

Solution that supports any comparable types of indexes:

NSArray<NSString*> *unsortedArray = @[@"Alex", @"Rachel", @"Mohamad", @"Andrew"];
NSArray<NSNumber*> *indexArray = @[@1, @12, @23, @12];

NSParameterAssert([indexArray count] == [unsortedArray count]);
NSArray* sorted = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    NSNumber* index1 = indexArray[[unsortedArray indexOfObjectIdenticalTo:obj1]];
    NSNumber* index2 = indexArray[[unsortedArray indexOfObjectIdenticalTo:obj2]];

    NSComparisonResult result = [index1 compare:index2];
    return result;
}];

NSLog(@"Sorted array: %@", 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.