按日期分组并用JS计算平均值

时间:2019-12-16 11:31:13

标签: javascript arrays group-by reduce

我有一个带有时间戳和一些参数的数据集。看起来像这样:

const resp = [
    {date: 1576098000, responseBot: 0.47, responseManager: 2.0},
    {date: 1576098000, responseBot: 1.50, responseManager: null},
    {date: 1576098000, responseBot: 1.05, responseManager: 2.3},
    {date: 1576108800, responseBot: 1.00, responseManager: 3.3},
    {date: 1576108800, responseBot: 0.60, responseManager: 1.5},
]
...

我需要得到一个分组的结果(按日期)并计算平均响应(机器人和管理者)。预期结果:

[
    {date: 1576098000, responseBotAvg: 1.006, responseManagerAvg: 2.15},
    {date: 1576108800, responseBotAvg: 0.8, responseManagerAvg: 2.4}
]

在纯JavaScript中达到此结果的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

第一步是使用date方法和reduce结合使用concat键对数组进行分组

然后只需将average除以元素的 number 即可找出total sum

const resp = [
    {date: 1576098000, responseBot: 0.47, responseManager: 2.0},
    {date: 1576098000, responseBot: 1.50, responseManager: null},
    {date: 1576098000, responseBot: 1.05, responseManager: 2.3},
    {date: 1576108800, responseBot: 1.00, responseManager: 3.3},
    {date: 1576108800, responseBot: 0.60, responseManager: 1.5},
]
var result = resp.reduce(function(h, obj) {
  h[obj.date] = (h[obj.date] || []).concat(obj);
  return h; 
}, {});
result = Object.keys(result).map(key => {
  return {
      date: key, 
      responseBotAvg : result[key].reduce((a, b) => a + (b.responseBot || 0), 0)/result[key].length,
      responseManagerAvg : result[key].reduce((a, b) => a + (b.responseManager || 0), 0)/result[key].map(({responseManager}) => responseManager).filter(Boolean).length,
  }
});
console.log(result);