0

Suppose I have an array of object as:

const timeValue = ["October 2020"]
const information = [
    {name: 'alpha',details: [
        {"attachment": [123, 456], "receivedOn":"2020-10-24 04:05:16.000Z"},
        {"attachment": [1454, 1992], "receivedOn":"2020-10-24 04:05:16.000Z"}]}, 
    {name: 'beta',details: [
        {"attachment": ["12", 189] ,  "receivedOn":"2020-10-24 04:05:16.000Z"},
        {"attachment": ["maggi", 1890, 2000],  "receivedOn":"2021-02-24 04:05:16.000Z"},
        {"attachment": [1990, 2001, 2901], "receivedOn":"2020-12-24 04:05:16.000Z"}]},
    {name: 'theta',details: [
        {"attachment": [1902, 1189] ,  "receivedOn":"2021-10-24 04:05:16.000Z"}] }];

I want to get count of alpha and beta for given time value i.e. expected O/P as:
{"alpha":4, "beta":2}

For this I tried, I am able to get count of total attachment for each name .i.e.
{alpha: 4, beta: 8, theta: 2}

const result = information.reduce((acc, curr) => {
   if (acc[curr.name] === undefined) acc[curr.name] = 0;
       curr.details.forEach((d) => (acc[curr.name] += d.attachment.length));
       return acc;
}, {});

console.log(result) gives output as {alpha: 4, beta: 8, theta: 2}

But I want to get count of only attachment which are present in oct 2020. Is it possible to achieve? If any else information please let me know.

Sushant Rad
  • 249
  • 2
  • 10

2 Answers2

1

just add the condition in you forEach, if you are only interested in year month comp, you can do something like that:

var result = information.reduce((acc, curr) => {
   if (acc[curr.name] === undefined) acc[curr.name] = 0;
       curr.details.forEach((d) => {
            var receivedOn = new Date(d.receivedOn);
            acc[curr.name] += (receivedOn.getFullYear() == 2020 && receivedOn.getMonth() == 9 ? d.attachment.length : 0)});
       return acc;
}, {});

TOHB
  • 71
  • 2
0

In JavaScript you can compare dates the same way you compare numbers, by using the >, <, and = operators. So all you have to do is add a condition to check whether the date's within the acceptable range before adding the attachment length to your count.

const compareDate = new Date(d.receivedOn);
if (compareDate >= new Date('10-01-2020') && compareDate <= new Date('10-31-2020')) {
  acc[curr.name] += d.attachment.length;
}
yev
  • 65
  • 1
  • 6