I have an array of objects with property date
.
What I want is to create array of arrays where each array will contain objects with the same date.
I understand, that I need something like .filter
to filter objects, and then .map
to add every thing to array.
But how to tell .map
that I want separate array for each group from filtered objects and that this array must be added to "global" array and how to tell .filter
that I want objects with the same date ?
It might be late but new Xcode 9 sdk dictionary has new init method
Documentation has simple example what this method does. I just post this example below:
Result will be:
improving on oriyentel solution to allow ordered grouping on anything:
Then it will work on any tuple, struct or class and for any property:
Rapheal's solution does work. However, I would propose altering the solution to support the claim that the grouping is in fact stable.
As it stands now, calling
grouped()
will return a grouped array but subsequent calls could return an array with groups in a different order, albeit the elements of each group will be in the expected order.Now that we track the order that we discover new groupings, we can return a grouped array more consistently than just relying on a Dictionary's unordered
values
property.+1 to GolenKovkosty answer.
More Examples:
Equilvalent to
In your case:
Output:
Abstracting one step, what you want is to group elements of an array by a certain property. You can let a map do the grouping for you like so:
Note that this grouping is stable, that is groups appear in order of appearance, and inside the groups the individual elements appear in the same order as in the original array.
Usage Example
I'll give an example using integers; it should be clear how to use any (hashable) type for
T
, includingDate
.