Ehsan Nissar
Ehsan Nissar

Reputation: 683

Count array items by month and year

I am getting dates in json of multiple parcels. the dates usually tells on which date and time that particular parcels was created. So with that date I want to count number of parcels created in each month. I have never done this before and i am not sure what thread of stackoverflow can help me out in this regard. I would very much appreciate any explanation to solve this help or a code reference. Here is my sample JSON result

[
  {
    "createdAt": "2019-12-30T04:36:05.001Z"
  },
  {
    "createdAt": "2019-12-06T08:58:23.030Z"
  },
  {
    "createdAt": "2020-01-08T19:00:21.873Z"
  },
  {
    "createdAt": "2020-01-10T14:55:50.781Z"
  },
  {
    "createdAt": "2019-12-21T13:05:09.983Z"
  },
  {
    "createdAt": "2020-01-15T12:10:20.316Z"
  },
  {
    "createdAt": "2020-01-14T06:47:36.078Z"
  },
  {
    "createdAt": "2020-02-15-T06:47:36.078Z"
  }
]

I am working with angular so i am getting this data from my service. So now i need to show month wise total number of parcels created.

Upvotes: 2

Views: 871

Answers (2)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

You can use Array.prototype.reduce() to summarize your records.

const src = [{"createdAt":"2019-12-30T04:36:05.001Z"},{"createdAt":"2019-12-06T08:58:23.030Z"},{"createdAt":"2020-01-08T19:00:21.873Z"},{"createdAt":"2020-01-10T14:55:50.781Z"},{"createdAt":"2019-12-21T13:05:09.983Z"},{"createdAt":"2020-01-15T12:10:20.316Z"},{"createdAt":"2020-01-14T06:47:36.078Z"},{"createdAt":"2020-02-15T06:47:36.078Z"}],
      summary = src.reduce((res,{createdAt}) => {
        const year = new Date(createdAt).getFullYear(),
              month = new Date(createdAt).getMonth()+1           
        res[`${year}-${month}`] = (res[`${year}-${month}`] || 0) + 1
        return res
      }, {})
      
console.log(summary)      

Note, above will work if your createdAt strings formatted in any way that may be parsed by new Date() constructor, not only ISO-formatted date.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386654

You could get a part of the ISO 8601 date string as key and count with an object.

var data = [{ createdAt: "2019-12-30T04:36:05.001Z" }, { createdAt: "2019-12-06T08:58:23.030Z" }, { createdAt: "2020-01-08T19:00:21.873Z" }, { createdAt: "2020-01-10T14:55:50.781Z" }, { createdAt: "2019-12-21T13:05:09.983Z" }, { createdAt: "2020-01-15T12:10:20.316Z" }, { createdAt: "2020-01-14T06:47:36.078Z" }, { createdAt: "2020-02-15-T06:47:36.078Z" }],
    result = data.reduce((r, { createdAt }) => {
        var key = createdAt.slice(0, 7);
        r[key] = (r[key] || 0) + 1;
        return r;
    }, {});

console.log(result);

Upvotes: 2

Related Questions