Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group elements of an array by some property

Tags:

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 ?

like image 457
Alexey K Avatar asked Jan 10 '17 08:01

Alexey K


1 Answers

It might be late but new Xcode 9 sdk dictionary has new init method

init<S>(grouping values: S, by keyForValue: (S.Element) throws -> Key) rethrows where Value == [S.Element], S : Sequence 

Documentation has simple example what this method does. I just post this example below:

let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"] let studentsByLetter = Dictionary(grouping: students, by: { $0.first! }) 

Result will be:

["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]] 
like image 97
golenkovkostya Avatar answered Oct 01 '22 05:10

golenkovkostya