How can I group nested collections based on column values, which are dynamically given? For example, suppose we have the following nested collections; how can I group it by the values in first and second columns?
[ ["A" 2011 "Dan"]
["A" 2011 "Jon"]
["A" 2010 "Tim"]
["B" 2009 "Tom"] ]
The desired resulting map is:
{ A {
2011 [['A', 2011, 'Dan'] ['A', 2011, 'Joe']]
2010 [['A', 2010, 'Tim']]
}
B { 2009 [['B', 2009, 'Tom']] }
}
Following is my solution, which almost works:
(defn nest [data criteria]
(if (empty? criteria)
data
(for [[k v] (group-by #(nth % (-> criteria vals first)) data)]
(hash-map k (nest v (rest criteria))))))
Here’s the solution I came up with. It works, but I’m sure it can be improved.