Search code examples
javascriptarrayssortingpolymerlocal-storage

How to sum values over a given date range


I'm using LocalStorage to save an array of Dates and Costs. When I'm writing localStorage.getItem("todos"); into the console, the format will be like this:

"[{"due":"28/10/2017","task":"80"},{"due":"06/10/2017","task":"15"}]"

Where due is the Date, and TASK is the AMOUNT.

I managed to get the TOTAL of AMOUNTS by:

total: {
  type: String,
  value: () => {
    var values = localStorage.getItem("todos");
    if (values === undefined || values === null) {
      return "0";
    }
    var data = JSON.parse(values);
    var sum = 0;
    data.forEach(function(ele){ sum+=Number(ele.task)}); return sum;
  }
}

Now I'm trying to get the TOTAL of last 6 MONTHS. I have no idea on how to approach this. How should I be able to do this?


Solution

  • During your iteration you need to add a check to make sure the sum is only including values where the due date is within your range. If you can use a library like moment, this would greatly simplify your logic.

    const data = [
      { due: '28/10/2017', task: 80 },
      { due: '06/10/2017', task: 15 },
      { due: '10/05/2000', task: 3000 }
    ];
    
    const sixMonthsAgo = moment().subtract(6, 'months');
    
    const total = data.reduce((acc, item) => {
      const dueDate = moment(item.due, 'DD/MM/YYYY');
      return acc + (dueDate.isAfter(sixMonthsAgo) ? item.task : 0);
    }, 0);
    
    console.log('total should equal 95: ', total);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>