2

I have an instance of NSArray with instances of NSArray inside. The inner arrays contain only instances of NSString. I need to sort the nested arrays alphabetically by a selected index.

E.g.

@[
  @[@"test",@"B",@"test2"],
  @[@"bla",@"A",@"bla"],
  @[@"xyz",@"C",@"123"]
]

User selects index 1, Ascending sort. Result should be:

@[
  @[@"bla",@"A",@"bla"],
  @[@"test",@"B",@"test2"],
  @[@"xyz",@"C",@"123"]
]

1 Answer 1

3

You can use sortedArrayUsingComparator:

NSArray *array = @[@[@"test",@"B",@"test2"],
                   @[@"bla",@"A",@"bla"],
                   @[@"xyz",@"C",@"123"]];

NSInteger index = 1;

NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    return [obj1[index] compare:obj2[index] options:NSCaseInsensitiveSearch];
}];

Clearly, if the subarrays have different number of items or if they're not all strings, you might include some additional logic to handle that, but it illustrates the basic idea.

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

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.