Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created April 9, 2014 02:58
Show Gist options
  • Save joyrexus/10222111 to your computer and use it in GitHub Desktop.
Save joyrexus/10222111 to your computer and use it in GitHub Desktop.
Pivot an array of objects by key

Accumulate values by key from an array of objects (key/value mappings):

records = [
  { a: 10, b: 20, c: 30 }, 
  { a: 11, b: 21 }, 
  { a: 12, b: 22, c: 32, d: 42 }
]

pivoted = pivot(records)

Expected result:

pivoted = { 
  a: [ 10, 11, 12 ], 
  b: [ 20, 21, 22 ], 
  c: [ 30, 32 ], 
  d: [ 42 ] 
}
# reducing iterator
iter = (pivoted, rec) ->
for k, v of rec
pivoted[k] = [] if not pivoted[k]
pivoted[k].push(v)
pivoted
module.exports = pivot = (data) -> data.reduce(iter, {})
module.exports = pivot;
function pivot(data) {
var iter = function(pivoted, record) {
for (var key in record) {
if (!pivoted[key]) pivoted[key] = []
pivoted[key].push(record[key])
}
return pivoted;
};
return data.reduce(iter, {})
};
pivot = require 'pivot'
{deepEqual} = require 'assert'
# data to be pivoted should be an array of records
records = [
{ a: 10, b: 20, c: 30 },
{ a: 11, b: 21 },
{ a: 12, b: 22, c: 32, d: 42 }
]
expected =
a: [ 10, 11, 12 ]
b: [ 20, 21, 22 ]
c: [ 30, 32 ]
d: [ 42 ]
deepEqual pivot(records), expected
@NiceYellowEgg
Copy link

Worked for me nicely :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment