GroupBy without Count

Hi everyone,

I would like select from a table and group all element by a column of table. it possible?

for example:

SELECT * FROM Kanji GROUP BY numStroke

I would that return me a dictionary in which there is

[
{“Stroke 1” : Array}
{“Stroke 2” : Array}

]

so I can use this array to put in table divided in section where every section is the array ok Kanji*

*Kanji is subclass of NSManagedObject class

It possible?

Thanks
p.s. now I’m learning swift. then swift code is ok!

hi @rufy,
your question is not worded appropriately to understand what you are really after, perhaps re-iterating it would help resolve.

if you are trying to create the data in a way that it can be used with a TableView directly, then the code snip you have shown can still work as is. If you re-iterate your question, could help you better.

cheers,

Jayant

The question is: How can I group a set of data by an element of this data?. E.g. Person(name, surname, department); Department(name, address, work). I would like have an array that has for every department NOT the number of persons who are working in that department, but the persons that are working in that department; the function GroupBy return an array of dictionary in which there is the department like key, and the number of person like value. Would like an Array of dictionary in which there are the department like key and an array of person like a value.

is it possible?

Hi @rufy,
You could get the data in the way you want by altering your SQL statements, or if you are using REST API, then you could return the data accordingly.

If you want to transpose the data in swift/code that can be done.

struct Person {
    var name: String
    var surname: String
    var department: String
}

struct Department {
    var name: String
    var address: String
    var work: String
}

let departments: [Department] = [
    Department(name: "IT", address: "", work: ""),
    Department(name: "Sales", address: "", work: ""),
    Department(name: "Contact", address: "", work: "")
]

let persons: [Person] = [
    Person(name: "John", surname: "Doe", department: "IT"),
    Person(name: "Jane", surname: "Doe", department: "Sales"),
    Person(name: "James", surname: "Doe", department: "IT"),
    Person(name: "Jinny", surname: "Doe", department: "Contact"),
    Person(name: "Juan", surname: "Doe", department: "Sales"),
    Person(name: "Andrew", surname: "Doe", department: "IT"),
    Person(name: "Ben", surname: "Doe", department: "IT"),
]

let depts = departments.compactMap{ return $0.name}
var results:[String:[Person]] = [:]

depts.forEach { dept in
    results[dept] = persons.filter({ $0.department == dept}).map{$0}
}

dump(results)

Hope this was what you were after

cheers,

Jayant