imstillalive
imstillalive

Reputation: 369

Sort NSArray with array of index numbers

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?

Upvotes: 1

Views: 549

Answers (2)

Andrew Romanov
Andrew Romanov

Reputation: 5076

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);

Upvotes: 0

dev gr
dev gr

Reputation: 2431

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.

Upvotes: 5

Related Questions