G.P.Reddy G.P.Reddy - 2 months ago 6
Objective-C Question

Get Index of Object on Array without duplicates

I've an two different arrays here

[
"21:55",
"21:55",
"21:55",
"22:00",
"21:55"
]


i am using above two arrays to sorting like this below code,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];

NSArray *sortedTimes = [timeArraySorting sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
{
NSDate *date1 = [dateFormatter dateFromString:obj1];
NSDate *date2 = [dateFormatter dateFromString:obj2];
return [date1 compare:date2];
}];
NSLog(@"Start sortedTimes= %@",sortedTimes);


after sorting second Array like this,

sortedTimes = [
"21:55",
"21:55",
"21:55",
"21:55",
"22:00"
]


but i need to compare second array to first array to get indexes of first array.but here i get duplicates like this,

[
0,
0,
0,
0,
3
]


but i need like this,

[
0,
1,
2,
4,
3
]


Can you please suggest me how can i solve this?
Thank you.

Answer

One way is to add indexes to the original array and sort those too, along with the string data...

// data from the OP
NSArray *timeArraySorting = @[
                   @"21:55",
                   @"21:55",
                   @"21:55",
                   @"22:00",
                   @"21:55"
                   ];

// add index data to it, so it has the form:
//  @[ [ @"21:55", @0], [ @"21:55", @1], ...
NSMutableArray *indexedTimeArray = [@[] mutableCopy];
for (int i=0; i<timeArraySorting.count; i++) {
    [indexedTimeArray addObject: @[timeArraySorting[i], @(i)] ];
}

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];

// sort that indexed data
NSArray *sortedTimes = [indexedTimeArray sortedArrayUsingComparator:^NSComparisonResult(NSArray *obj1, NSArray *obj2) {
    NSDate *date1 = [dateFormatter dateFromString:obj1[0]];
    NSDate *date2 = [dateFormatter dateFromString:obj2[0]];
    return [date1 compare:date2];
}];
NSLog(@"Start sortedTimes= %@",sortedTimes);

Output looks like this:

Start sortedTimes= (
    (
    "21:55",
    0
),
    (
    "21:55",
    1
),
    (
    "21:55",
    2
),
    (
    "21:55",
    4
),
    (
    "22:00",
    3
)
)

Run through that array to pickup the sorted result and the sorted indexes...

NSMutableArray *result = [@[] mutableCopy];
NSMutableArray *indexes = [@[] mutableCopy];

for (NSArray *a in sortedTimes) {
    [result addObject:a[0]];
    [indexes addObject:a[1]];
}

NSLog(@"result is %@", result);
NSLog(@"indexes is %@", indexes);

Tested to match the OP desired result.