# How to sum values over a given date range

###### Posted By: Anonymous

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.

_x000D_

_x000D_

```
const data = [_x000D_
{ due: '28/10/2017', task: 80 },_x000D_
{ due: '06/10/2017', task: 15 },_x000D_
{ due: '10/05/2000', task: 3000 }_x000D_
];_x000D_
_x000D_
const sixMonthsAgo = moment().subtract(6, 'months');_x000D_
_x000D_
const total = data.reduce((acc, item) => {_x000D_
const dueDate = moment(item.due, 'DD/MM/YYYY');_x000D_
return acc + (dueDate.isAfter(sixMonthsAgo) ? item.task : 0);_x000D_
}, 0);_x000D_
_x000D_
console.log('total should equal 95: ', total);
```

_x000D_

`<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>`

_x000D_

_x000D_

_x000D_

###### Answered By: Anonymous

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.