-1

I have a dataset with the timestamp and some params. It looks like that:

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},
]
...

I need to get a grouped result (by date) and count an average of response (bot and manager). Expected result:

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

What is the best way to achieve this result in pure javascript?

Nataly Firstova
  • 661
  • 1
  • 5
  • 12

1 Answers1

1

The first step is to group the array by date key using reduce method in combination with concat.

Then just find out the average by dividing the total sum to the number of elements.

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);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128