简体   繁体   中英

How to get Unique NSDictionary from NSArray of NSDictionary

I am using Objective C on iOS 9.

I want to get Unique NSDictionaries from NSArray of NSDictionary .

I have N numbers of NSDictionaries which look like bellow (for example):

staff     Description   Price
*****     ***********   *****
01       'some string'  9.99
05       'some string'  8.80
01       'some string'  7.45
01       'some string'  4.21

How to achieve my goal from these?

The unique parameter is staff .

I want to get Unique NSArray for each, as:

{
        @[
            @[@{@"staff":01,@"description":@"some string",@"price":9.88},
              @{@"staff":01,@"description":@"some string",@"price":7.45},
              @{@"staff":01,@"description":@"some string",@"price":4.21}
            ],
            @[@{@"staff":05,@"description":@"some string",@"price":8.80}
            ],
        ];
    }
 

This question might look like a possible duplicate of this , but there is a difference, that I don't want sorted data in any manner. Second, I want array of those dictionaries which key-> staff is similar.

Thanks to 'Mr.T' for providing this link.
after digging into that link, i managed to achieve my goal

    //Step:-1 prepare your inputArray having NSDictionaries

    //Step:-2 now,check that how many unique values avilable in inputArray
    NSMutableSet* _info = [[NSMutableSet alloc]init];
    [inputArray enumerateObjectsUsingBlock:^(NSDictionary* info, NSUInteger index, BOOL* stop){
        [_info addObject:[info valueForKey:@"staff"]];
    }];
    NSLog(@"Unique Value:->\n%@",[_info allObjects]);

    //Step:-3 now,run loop till count of unique objects and use NSPredicate to get filtered array like bellow,
    //        you can use for..in.. OR for(int i=0;.....) OR Other but i preffer block
    [_info.allObjects enumerateObjectsUsingBlock:^(NSString* staff, NSUInteger index, BOOL* stop){
        NSMutableDictionary* info = [[NSMutableDictionary alloc]init];
        [info setValue:staff forKey:@"table"];
        NSArray *filtered = [inputArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(staff == %@)", staff]];
        [info setValue:[NSMutableArray arrayWithArray:filtered] forKey:@"data"];

        NSLog(@"\nFiltered Array:->\n%@",info);
    }];

by the way, thank you so much guys for paying attention on my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM