-1

I have an array of 50 objects with value and ISOString date format.

const totalIncome = [ 
  {value: '5419.59',
   date: '2019-11-20T00:03:09.496Z'},
  {value: '1242.41',
   date: '2019-12-08T03:08:30.016Z'},
  {value: '3242.41',
   date: '2019-12-08T03:08:30.016Z'},
      ...
];

How can I return sum of all values that are from last month (all values from December)? I want to do it in vanilla JS.

2 Answers2

1
  • Set the month and year you care about
  • Filter the array down to objects inside that month & year
  • Reduce the array down to the sum of all remaining value

Keep in mind that the below is just for demonstration purposes, new Date may not always parse date strings in the way you expect and there are timezones to consider. If you have full ISO strings and consider last month to respect the local timezone of the device running this script, then it might be ok.

const totalIncome = [{
    value: '5419.59',
    date: '2019-11-20T00:03:09.496Z'
  },
  {
    value: '1242.41',
    date: '2019-12-08T03:08:30.016Z'
  },
  {
    value: '3242.41',
    date: '2019-12-08T03:08:30.016Z'
  },
];

const today = new Date();
let lastMonth = today.getMonth() - 1;
let relevantYear = today.getYear();

if (lastMonth === -1) {
  relevantYear--;
  lastMonth = 11;
}

const total = totalIncome.filter(i => {
  const date = new Date(i.date);

  return date.getMonth() === lastMonth && date.getYear() === relevantYear;
}).reduce((prev, curr) => prev + parseFloat(curr.value), 0);

console.log(total);
ed'
  • 1,815
  • 16
  • 30
0
var sum = lastMonthIncome.reduce((accVal, crntObj) => {
  if (crntObj.date.includes("2019-11")) {
    return accVal + crntObj.value;
  } else {
    return accVal;
  }
}, 0);

here you can change includes("2019-11") as per your required month.

Ayyappa Gollu
  • 906
  • 7
  • 16