Skip to content

Instantly share code, notes, and snippets.

@kanghyojun
Created June 8, 2013 12:32
Show Gist options
  • Select an option

  • Save kanghyojun/5735020 to your computer and use it in GitHub Desktop.

Select an option

Save kanghyojun/5735020 to your computer and use it in GitHub Desktop.
scala groupBy in Coffeescript
a = [
{'id': 1, 'ca': 123}, {'id': 2, 'ca': 321}, {'id': 3, 'ca': 213}
]
Array.prototype.groupBy = (key, callback) ->
res = {}
if key is undefined
throw "key cannot be undefined. you MUST define key function."
for i in this
do (i) ->
k = key(i)
if typeof(k) isnt "string"
throw "key must return `string`"
if !res.hasOwnProperty(k)
res[k] = []
res[k].push(i)
callback(res)
keyFunc = (i) ->
r = i.ca % 100
parseInt(r / 10).toString()
a.groupBy keyFunc, (r) ->
console.log(r) # { '1': [ { id: 3, ca: 213 } ], '2': [ { id: 1, ca: 123 }, { id: 2, ca: 321 } ] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment