-1

I have a UITableView and am displaying contents from my NSMutableArray. Following is array format

 (
  {

        Name = "ANS";
        VersionNo = 6;

    },
        {

        Name = "O-Hydro";
        Version = 6;

    },
        {

        Name = "ANS";
        Version = 6;

    },
        {

        Name = "ANTIChorosAnticholinergic";
        Version = 6;

    }
)

From this I need to display only unique "Name" (like in this I can see 2 "ANS" I need only one).

How can I do this in iOS?

I tried following but its not working

uniqueArray= [[NSMutableSet setWithArray: groupDetails] allObjects];

but in this way I can do only for NSArray not NSMutableArray.

Pls help me

Indrajeet
  • 5,490
  • 2
  • 28
  • 43
john mike mike
  • 125
  • 1
  • 3
  • 13
  • Follow these posts http://stackoverflow.com/questions/22236134/filtration-by-comparison-of-dictionary-objects-in-nsarray and also check this http://stackoverflow.com/questions/16226696/remove-duplicate-valuse-from-nsmutable-array – srinivas n Nov 07 '14 at 12:20

3 Answers3

0

You can use following line of code to convert your NSArray to NSMutableArray,

NSArray *uniqueArray= [[NSMutableSet setWithArray:groupDetails] allObjects];
NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithArray:uniqueArray];
Deepak
  • 1,421
  • 1
  • 16
  • 20
0

If you just want an array of unique name values, you can use @distinctUnionOfObjects with valueForKeyPath -

NSArray *uniqueArray=[groupDetails valueForKeyPath:@"@distinctUnionOfObjects.name"];

But if you want the array to contain the dictionaries that correspond to the unique names then you need to do a little more work -

NSMutableArray *uniqueArray=[NSMutableArray new];
NSMutableSet *nameSet=[NSMutableSet new];

for (NSDictionary *dict in groupDetails) {
    NSString *name=dict[@"name"];
    if (![nameSet containsObject:name]) {
        [uniqueArray addObject:dict];
        [nameSet addObject:name];
    }
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
0

You could simply add mutableCopy.

But wait, before you do it. Arrays and sets have two differences:

  1. Arrays can contain duplicates, sets cannot.
  2. Arrays are ordered, sets are not.

So doing what you are doing, you lose the duplicates (intentionally), but the order, too (probably not intentionally).

I do not know, whether this is important for you, but for other readers it might be. So it is the better approach to do that with NSOrderedSet instead of NSSet:

NSOrderedSet *uniqueList = [NSOrderedSet orderedSetWithArray:array];

In many cases an ordered set is exactly what you want. (Probably it has been from the very beginning and the usage of NSArray was wrong. But sometimes you get an array.) If you really want an array at the end of the day, you can reconvert it:

array = [uniqueList.array mutableCopy];
Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50