2

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).

P. Nick
  • 955
  • 1
  • 12
  • 33
  • See here... https://stackoverflow.com/a/34890276/3739842 – Sean T Jan 07 '20 at 17:15
  • Does this answer your question? [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – Sean T Jan 07 '20 at 17:16
  • Just to clarify: You still need this intermediate `temp` array? I don't think it's helpful for solving the problem, you could just implement the solution in the loop you're using to build `temp`. – Klaycon Jan 07 '20 at 17:16
  • @Klaycon `temp` is not needed, no. I will look into those other answers too :) – P. Nick Jan 07 '20 at 17:20

1 Answers1

1

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);
Klaycon
  • 10,599
  • 18
  • 35