javascript - Sum Of count in D3 -


i have json data below.

[    {     "avg": 996.8,     "sessions": [        {         "mintime": 0,         "maxtime": 599,         "count": 10       },       {         "mintime": 600,         "maxtime": 1199,         "count": 2       },       {         "mintime": 1800,         "maxtime": 2399,         "count": 4       },       {         "mintime": 2400,         "maxtime": 2999,         "count": 3       }     ],"timestamp":1449360000},   {     "avg": 986.4,     "sessions": [        {         "mintime": 0,         "maxtime": 599,         "count": 12       },       {         "mintime": 600,         "maxtime": 1199,         "count": 1       },       {         "mintime": 1200,         "maxtime": 1799,         "count": 2       },       {         "mintime": 1800,         "maxtime": 2399,         "count": 2       },       {         "mintime": 3000,         "maxtime": 3599,         "count": 3       }     ]     ,"timestamp":1449540000}] 

and need data as

[{"avg" : 996.8,"sumcount" :19 , "timestamp":1449360000 } {"avg": 986.4, "sumcount" :20 ,"timestamp":1449540000 }] 

i tried ( know code not correct, still adding) nest() getting count=0

d3.json("dwell.json", function(error,data){   var res = d3.nest()             .key(function(d) { return d.avg; })             .rollup(function(v) { return d3.sum(v, function (d) {return d.count})})             .entries(data);     console.log(json.stringify(res)); }) 

and result [{"key":"996.8","values":0},{"key":"986.4","values":0}]

in plain javascript can use array.prototype.map() , array.prototype.reduce() collecting count , mapping objects.

var data = [{ "avg": 996.8, "sessions": [{ "mintime": 0, "maxtime": 599, "count": 10 }, { "mintime": 600, "maxtime": 1199, "count": 2 }, { "mintime": 1800, "maxtime": 2399, "count": 4 }, { "mintime": 2400, "maxtime": 2999, "count": 3 }], "timestamp": 1449360000 }, { "avg": 986.4, "sessions": [{ "mintime": 0, "maxtime": 599, "count": 12 }, { "mintime": 600, "maxtime": 1199, "count": 1 }, { "mintime": 1200, "maxtime": 1799, "count": 2 }, { "mintime": 1800, "maxtime": 2399, "count": 2 }, { "mintime": 3000, "maxtime": 3599, "count": 3 }], "timestamp": 1449540000 }],      result = data.map(function (a) {          return {              avg: a.avg,              sumcount: a.sessions.reduce(function (s, b) { return s + b.count; }, 0),              timestamp: a.timestamp          };      });    document.write('<pre>' + json.stringify(result, 0, 4) + '</pre>');


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -