P. Nick
P. Nick

Reputation: 991

Calculate average price of grouped dates by day

I am trying to figure out how I can get the average price of every day.

const groupByDay = _.groupBy(nextProps.data, (date) => {
    return moment.unix(date.createdAt).startOf("day").format();
});

const result = _.map(groupByDay, (group, day) => {
    return {
        date: day.split("T")[0],
        offers: group // all offers for the day
    }
});

const temp = [];
result.forEach((res) => {
    res.offers.forEach((rr) => {
        temp.push({date: res.date, avgPrice: rr.price});
    })
});

This will return the following temp array as seen below:

[
   {
      "date":"2020-01-07",
      "avgPrice":334
   },
   {
      "date":"2020-01-07",
      "avgPrice":756
   },
   {
      "date":"2020-01-02",
      "avgPrice":30
   }
]

But how I can make it group this and then calculate the average price of all objects with the same date value? E.g. avgPrice of 2020-01-07 should be 545 which is ((334+756)/2).

Upvotes: 2

Views: 110

Answers (1)

Klaycon
Klaycon

Reputation: 11080

Instead of creating an array of date-price entries (which you'd just have to group back together again!) realize that you already have a list of entries with dates and all prices for that date. All you need to do is, for each entry, turn the array of prices into one average price. A very easy operation with Array#reduce:

//example result value for display purposes
const result = [
    { date: "2020-01-07", offers: [334, 756] },
    { date: "2020-01-02", offers: [30] }
];

//important part, should work with your result array
let temp = result.map((res) => {
  return {
    date: res.date,
    avgPrice: res.offers.reduce((avg, price) => avg + price / res.offers.length, 0)
  };
});

console.log(temp);

Upvotes: 1

Related Questions