Home > database >  Get sum of array values based on date values of other array
Get sum of array values based on date values of other array

Time:12-29

So i have problem like this:

I have 2 arrays:
one from mysql query that contains date when order have been created and total sum of it

const ordersData = [
0: {id: 1, data: '2021-11-23T00:00:00.000Z', price: 394}
1: {id: 2, data: '2021-11-23T00:00:00.000Z', price: 315.3}
2: {id: 3, data: '2021-11-23T00:00:00.000Z', price: 16445}
...
6: {id: 7, data: '2021-11-23T00:00:00.000Z', price: 200}
7: {id: 8, data: '2021-12-22T00:00:00.000Z', price: 618}

]


second is array is where i have monthly sum, month, first and last day of month

const pastMonthsData = [
   0: {
    month: "december",
    firstDay: Wed Dec 01 2021,
    lastDay: Fri Dec 31 2021,
    totalMonthSum: x
 },
   1: {
    month: "november",
    firstDay: Mon Nov 01 2021,
    lastDay: Tue Nov 30 2021,
    totalMonthSum: x
 }
]

I need to check if date from order array is in between date of pastMonthsData and add price to totalMonthSum.
So far i created func like this but it only works for december, for november there is no result.

pastMonthsData.forEach((el, i) => {
        el.totalMonthSum = ordersData.reduce((total, item) => {
          let itemDate = new Date(item.data);
          if(el.firstDay.getTime() < itemDate.getTime() && itemDate.getTime() < el.lastDay.getTime()) {
            return total   item.price
          } else {
            return 0
          }
        })
      });

CodePudding user response:

Two fixes:

  1. initialize the accumulated total to zero
  2. return the accumulated total, rather than zero, when a date is not in range

For example:

pastMonthsData.forEach((el, i) => {
  el.totalMonthSum = ordersData.reduce((total, item) => {
    let itemDate = new Date(item.data);
    if (el.firstDay.getTime() < itemDate.getTime() && itemDate.getTime() < el.lastDay.getTime()) {
      return total   item.price;
    } else {
      return total;
    }
  }, 0)
});
  • Related