I recently posted this question about summing arrays in JavaScript using d3.nest ()
I got a good solution (two actually), but it turned out that both have a problem when they are adapted to add additional information:
data = [ { continent: 'africa', country: 'gabon', values: [1, 2] }, { continent: 'africa', country: 'chad', values: [3, 4] }, { continent: 'asia', country: 'china', values: [1, 2] } ]; sum_by = 'continent'; rollupAgg = function(data, sum_by) { return d3.nest().key(function(d) { return d[sum_by]; }).rollup(function(group) { return group.reduce(function(prev, cur, index, arr) { return { values: prev.values.map(function(d, i) { return d + cur.values[i]; }), sum_by: sum_by
reduce () does not start if there is only one line in this group, so this returns the following:
[ { "key": "africa", "values": { "values": [4, 6], "sum_by": "continent" } }, { "key": "asia", "values": { "continent": "asia", "country": "china",
Can you see a way to change this function so that it returns the desired result?
source share