Note that there are some explanatory texts on larger screens.

plurals
  1. POSplit an NSArray in smaller key value coded arrays using a common key-value pair between objects
    primarykey
    data
    text
    <p><br> I'm trying to find a good solution to split an array of dictionaries in a smaller dictionaries keyed by a common value between them. <br> Here is an example i JSON, I start from this:</p> <pre><code>{ "field": [ { "id": 6, "name": "Andrea" }, { "id": 67, "name": "Francesco" }, { "id": 8, "name": "Maria" }, { "id": 6, "name": "Paolo" }, { "id": 67, "name": "Sara" } ] } </code></pre> <p>I'd like to get a result like:<br></p> <pre><code>{ "field": [ { "6": [ { "name": "Andrea", "id": 6 }, { "name": "Paolo", "id": 6 } ], "67": [ { "name": "Sara", "id": 67 }, { "name": "Francesco", "id": 67 } ], "8": [ { "name": "Maria", "id": 8 } ] } ] } </code></pre> <p>I managed using this code, it works, but I'm wondering if exist something more correct and fast:<br></p> <pre><code> NSArray * array = ...; NSSortDescriptor *sorter1=[[NSSortDescriptor alloc]initWithKey:@"id" ascending:YES selector:@selector(compare:)]; NSSortDescriptor *sorter2=[[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]; NSArray *sortDescriptors=[NSArray arrayWithObjects:sorter1,sorter2,nil]; array = [array sortedArrayUsingDescriptors:sortDescriptors]; //////////////////////////////SPLITTER NSMutableArray * subcategorySplittedArray = [[NSMutableArray alloc]initWithCapacity:30]; NSNumber * lastID=[[array objectAtIndex:0]objectForKey:@"id"]; NSMutableArray * shopArray = [[NSMutableArray alloc]initWithCapacity:100]; NSMutableDictionary * catDict = nil; for (NSDictionary * dict in array) { NSNumber * catID = [dict objectForKey:@"id"]; if ([lastID isEqualToNumber:catID]) { [shopArray addObject:dict]; } else { catDict = [[NSMutableDictionary alloc]init ]; [catDict setObject:[shopArray copy] forKey:lastID]; [subcategorySplittedArray addObject:catDict]; [shopArray removeAllObjects]; [shopArray addObject:dict]; lastID = catID; } } catDict = [[NSMutableDictionary alloc]init ]; [catDict setObject:[shopArray copy] forKey:lastID]; [subcategorySplittedArray addObject:catDict]; //////////////////////////////////// return subcategorySplittedArray; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload