Calculate average of average using crossfilter/reductio

I am attempting to calculate the average miles the average car drives grouped by hour of the day. I have a sample data set that looks like this:

[{date: 1/1/2017, hour: 9, car: 12, miles: 5},
 {date: 1/1/2017, hour: 9, car: 13, miles: 82},
 {date: 1/2/2017, hour: 9, car: 13, miles: 17},
 {date: 1/2/2017, hour: 10, car: 12, miles: 15},
 {date: 1/2/2017, hour: 10, car: 13, miles: 2}]

The resultant data set should be:

[{hour: 9, averageMiles: 27.25},
 {hour: 10, averageMiles: 8.5}]

Using this question I was able come up with a working solution. However, it appears to be fairly verbose and I was wondering if there is a better way to do this, perhaps using reductio. Here's the main part of the solution I came up with. See the fiddle below for the full solution.

grp1 = hourDimension.group().reduce(
  function(p, v) { // add
    var car = v.car;
    var mappedCar = p.map.has(car) ? p.map.get(car) : {
      count: 0,
      sum: 0,
      avg: 0
    }
    mappedCar.count += 1;
    mappedCar.sum += v.miles;
    mappedCar.avg = mappedCar.sum / mappedCar.count;
    p.map.set(car, mappedCar);
    p.avg = average_map(p.map);
    return p;
  },
  function(p, v) { // remove
    ...
  },
  function() { // init
    return {map: d3.map(), avg: 0};
  }
);    

Here is a working fiddle showing the results.

链接地址: http://www.djcxy.com/p/32822.html

上一篇: 交叉过滤器数据结构

下一篇: 使用交叉过滤器/还原计算平均值