Merge arrays with its count in Objective C

101 views Asked by At

I have an array like this

A = [@"aa",@"cc",@"bb",@"bb",@"cc",@"aa",@"cc"]

I need to convert it to

A = [@"x2 aa",@"x2 bb",@"x3 cc"]
1

There are 1 answers

2
Anoop Vaidya On BEST ANSWER

Count the similar elements and create a new string, add it to new array. As shown here:

NSArray *aArray = @[@"aa", @"cc", @"bb", @"bb", @"cc", @"aa", @"cc"];

NSCountedSet *set = [NSCountedSet setWithArray:aArray];

NSMutableArray *countedArray = [NSMutableArray new];
for (NSString *str in set) {
    [countedArray addObject:[NSString stringWithFormat:@"x%ld %@",[set countForObject:str], str]];
}

NSLog(@"%@",countedArray);

Output:

( "x2 bb", "x2 aa", "x3 cc" )