Skip to content

Instantly share code, notes, and snippets.

@thynson
Created September 9, 2014 15:52
Show Gist options
  • Save thynson/193bc81bbc7751d54aed to your computer and use it in GitHub Desktop.
Save thynson/193bc81bbc7751d54aed to your computer and use it in GitHub Desktop.
_ = require 'lodash'
###
aggr = aggregate (['a', 'b'])
aggr ([{ a: 1, b:1, c:1 },
{ a: 1, b:1, c:1 },
{ a: 1, b:1, c:2 },
{ a: 1, b:2, c:1 },
{ a: 1, b:2, c:2 },
{ a: 2, b:1, c:1 }])
-> [ { a: 1, b: 1, c:[1, 1, 2] },
{ a: 1, b: 2, c:[1, 2] },
{ a: 2, b: 1, c:[1] } ]
###
module.exports = (path)->
(array)->
tmp = {}
_.forEach array, (val, idx)->
t = tmp
_.forEach path, (p, i)->
if val[p] isnt undefined
if i < path.length-1
if t[val[p]] is undefined
t[val[p]] = {}
t = t[val[p]]
else
if t[val[p]] is undefined
t[val[p]] = []
t[val[p]].push val
t = _.toArray tmp
_.forEach path, (p, i)->
if i < path.length - 1
p = []
_.forEach t, (val)->
p.push _.toArray val
t = _.flatten p, true
result = []
_.forEach t, (coll)->
val = _.pick coll[0], path
_.forEach coll, (x)->
x = _.omit x, path
_.forEach x, (v, k)->
if val[k] is undefined
val[k] = []
val[k].push v
result.push val
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment