2

I feel like this is simple but I just can't wrap my head around it. I have an array of days of the week that a user can select against:

NSArray * daysOfTheWeek = [NSArray arrayWithObjects:@"sunday", @"monday", @"tuesday", @"wednesday", @"thursday", @"friday", @"saturday", nil];

I as the toggle the days on and off, I'd like to sort their NSArray fo selected days against the dayOfTheWeek NSArray. So if a user has:

NSArray * userDays = [NSArray arrayWithObjects:@"thursday", @"monday", @"friday"];

I want to sort this so that its monday, thursday, friday.

I'd seem some of the similar questions posted but none were clear enough for me to know how I could apply them to this. Could be my lack of sleep :)

Thank you!

2 Answers 2

5
NSArray *sortedUserDays = [userDays sortedArrayUsingComparator:^(id a, id b) {
    return [@([daysOfTheWeek indexOfObject:a]) compare:@([daysOfTheWeek indexOfObject:b])];
}];

Edit: This sorts the array using a block as a comparator.

To compare two elements of the userDays array it first searches their positions in the template array daysOfTheWeek: [daysOfTheWeek indexOfObject:a]

It then wraps the positions into NSNumbers: @(index).

Next it calls compare: on the wrapped indices. That's just a lazy way of returning an NSComparisonResult for the two NSUInteger positions.

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

1 Comment

Thanks very much this seems to do the trick. Would you or someone else please explain a bit about whats happening?
4

Another way you could do this is by simply filtering your days of the week with the users options.

NSArray *sortedUserDays = [daysOfTheWeek filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF in (%@)", userDays]];

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.