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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With