- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupByTwoKeysAndPivotValuesIntoArray.js
More file actions
Latest commit
34 lines (29 loc) · 1022 Bytes
/
Copy pathGroupByTwoKeysAndPivotValuesIntoArray.js
File metadata and controls
34 lines (29 loc) · 1022 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Produces one row for each unique combination of KeyA and KeyB with
// a Values property that is an array of values that match the
// given key combination.
// Requires: underscore/lodash
varraw=[
{KeyA: "A",KeyB: 11,Value: 100},
{KeyA: "A",KeyB: 11,Value: 200},
{KeyA: "A",KeyB: 22,Value: 300},
{KeyA: "A",KeyB: 33,Value: 350},
{KeyA: "B",KeyB: 11,Value: 400},
{KeyA: "B",KeyB: 11,Value: 500},
{KeyA: "B",KeyB: 22,Value: 600},
{KeyA: "B",KeyB: 22,Value: 700}
];
vargrouped=_.chain(raw)
.groupBy(function(x){returnx.KeyA+'_'+x.KeyB;})
.map(function(x){
varfirst=x[0];// At least one element always exists
varvalues=x.map(function(v){returnv.Value;});
return{KeyA: first.KeyA,KeyB: first.KeyB,Values: values};
})
.value()
console.log(grouped);
// Produces:
// [
// { KeyA: "A", KeyB: 11, Values: [ 100, 200 ] },
// { KeyA: "A", KeyB: 22, Values: [ 300 ] },
// ...
// ]