IMPORTANT: Note the comment from @RobG regarding the ability to compare ISO 8601 date strings lexically to avoid issues with Date.parse. See the updated answer below to reflect that comment, the original answer follows for reference.
UPDATE:
The following example removes the date parsing step when compared to the original.
const info = {"info": [{ "date": "2018-10-04T00:00:00.000Z", "number": "1" }, { "date": "2018-10-03T00:00:00.000Z", "number": "2" }, { "date": "2018-10-02T00:00:00.000Z", "number": "3" }, { "date": "2018-10-01T00:00:00.000Z", "number": "4" } ] };
const sum = info.info.reduce((acc, obj) => {
acc += parseInt(obj.number);
return acc;
}, 0);
const sumDate = info.info.reduce((acc, obj) => {
if (obj.date >= '2018-10-03T00:00:00.000Z') {
acc += parseInt(obj.number);
}
return acc;
}, 0);
console.log('sum', sum);
console.log('sumDate', sumDate);
ORIGINAL:
You need to parse the date strings for comparison and then you can just use reduce. If you prefer a for loop, see the corrections to your original code with some quick explanation below the snippet (as it applies to just summing all the values - you could modify the for loop with the same principles as seen below in the reduce approach).
sum below just gets a sum of all the number properties in your array of objects (fairly simple example of how to use reduce). sumDate below adds an if statement to compare the date properties in your array of objects before including the corresponding number in the sum (just hardcoded a date string for 2018-10-3 in the same format as your other data, but you could turn it into a function and pass the date as a parameter as well as determining whether to sum dates before or after the comparison date).
For example:
const info = {"info": [{ "date": "2018-10-04T00:00:00.000Z", "number": "1" }, { "date": "2018-10-03T00:00:00.000Z", "number": "2" }, { "date": "2018-10-02T00:00:00.000Z", "number": "3" }, { "date": "2018-10-01T00:00:00.000Z", "number": "4" } ] };
const sum = info.info.reduce((acc, obj) => {
acc += parseInt(obj.number);
return acc;
}, 0);
const sumDate = info.info.reduce((acc, obj) => {
if (Date.parse(obj.date) >= Date.parse('2018-10-03T00:00:00.000Z')) {
acc += parseInt(obj.number);
}
return acc;
}, 0);
console.log('sum', sum);
console.log('sumDate', sumDate);
To correct your original for loop attempt, the primary issue was that you were not incrementing your sum variable. Also, don't forget to declare the variables you are using with var (or even better with let or const).
var info = info.info;
var sum = 0;
for (var i = 0; i < info.length; i++) {
sum += parseInt(info[i].number);
}
console.log(sum);
// 10
console.logoutside theforloop. For the second question you need to tuse.filteron the array of elements and keep only those whose date is after/before the one you specify, before performing the addition.