Group NSDictionary by dates [duplicate]

2019-07-06 08:40发布

问题:

This question already has an answer here:

  • Grouping NSArray of NSDictionary based on a key in NSDictionay 2 answers

I have a NSDictionary and i want to group it creating an array of objects by date

Example of the main NSDictionary:

({

        date = "2014-04-27";
        group = "yellow.png";
        length = 180;

    },
        {

        date = "2014-04-28";
        group = "blue.png";
        length = 180;

    },
        {

        date = "2014-04-27";
        group = "blue.png";
        length = 120;

    })

I want to group something similar as:

2014-04-27 = (
{ 

            date = "2014-04-27";
            group = "yellow.png";
            length = 180;

        },
            {

            date = "2014-04-27";
            group = "blue.png";
            length = 180;

        })


  2014-04-28 = ( {

            date = "2014-04-28";
            group = "blue.png";
            length = 120;

        })

Could someone help me? i have tried many FOR but i cant get it

回答1:

It appears as though your original data structure is an array of dictionaries. Was your question phrased incorrectly? I see each individual dictionary but they are not keyed on anything in the top level data structure.

Assuming that is the case (you have an array called originalArray

NSMutableDictionary *dictionaryByDate = [NSMutableDictionary new];

for(NSDictionary *dictionary in originalArray)
{
    NSString *dateString = dictionary[@"date"];
    NSMutableArray *arrayWithSameDate = dictionaryByDate[dateString];
    if(! arrayWithSameDate)
    {
        arrayWithSameDate = [NSMutableArray new];
        dictionaryByDate[dateString] = arrayWithSameDate;
    }
    [arrayWithSameDate addObject: dictionary];
}

By the end of this, dictionaryByDate will be a dictionary (keyed on date) of arrays (all objects in a given array will be dictionaries with the same date).