Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get sum of array values based on date values of other array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
          }
        })
      });

>Solution :

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)
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading