Home > Software engineering >  array, count specific object by month
array, count specific object by month

Time:10-14

never done this before so go easy on me. I have a rather large array: that looks similar to this.

var data = [
    {"id": "1", "start_date":"2018-05-15 11:25:00", "priority": "P1"},
    {"id": "2", "start_date":"2019-05-15 11:25:00", "priority": "P2"},
    {"id": "3", "start_date":"2020-05-15 11:25:00", "priority": "P3"}]

I want get the count of each priority by month.

So far I've done this:

var result = [];


   result = data.reduce((r, {start_date, priority}) => {
     var p2 = priority === 'P2';
     var key = start_date.slice(0, 7);
     r[key] = (r[key] || 0)   1 && p2;
     return r;
    }, {});

    console.log(result);

which gives a true / false output and not the count.

2021-06: true
2021-07: false
2021-08: true
2021-09: true
2021-10: false

and by removing the && p2, it will count the total number like this:

2021-06: 11
2021-07: 18
2021-08: 11
2021-09: 9
2021-10: 5

Really appreciate some help.

CodePudding user response:

I am iterating every record And updating the count and month in a different object. This may help you

const data = [
    {"id": "1", "start_date":"2018-05-15 11:25:00", "priority": "P1"},
    {"id": "2", "start_date":"2019-05-15 11:25:00", "priority": "P2"},
    {"id": "3", "start_date":"2020-05-15 11:25:00", "priority": "P3"}
];

const priorityCount = {}

data.forEach(record => {

  const date = (new Date(record.start_date));
  const monthYear = `${date.getFullYear()}-${(date.getMonth()   1)}`;
  
  // Checking the year and month already exist, If not creating new
  if (!priorityCount[monthYear]) {
    priorityCount[monthYear] = {
      P1: 0,
      P2: 0,
      P3: 0
    };
  }
  
  // Updating the count of the relevant priority (P1/P2/P3)
  priorityCount[monthYear][record.priority]  ;
  
});

console.log(priorityCount);

CodePudding user response:

Here's another solution, using Array.reduce()

var data = [{
    "id": "1",
    "start_date": "2018-05-15 11:25:00",
    "priority": "P1"
  },
  {
    "id": "2",
    "start_date": "2019-05-15 11:25:00",
    "priority": "P2"
  },
  {
    "id": "3",
    "start_date": "2020-05-15 11:25:00",
    "priority": "P3"
  },
  {
    "id": "4",
    "start_date": "2020-05-15 11:25:00",
    "priority": "P3"
  },
  {
    "id": "5",
    "start_date": "2018-05-15 11:25:00",
    "priority": "P3"
  },
]

const byMonthByPrio = data.reduce((prevVal, curVal) => {
  const out = prevVal;
  const {
    start_date,
    priority
  } = curVal;
  const yearMonth = start_date.slice(0, 7);
  if (!out[yearMonth]) {
    out[yearMonth] = {};
  }
  if (!out[yearMonth][priority]) {
    out[yearMonth][priority] = 1;
  } else {
    out[yearMonth][priority]  ;
  }
  return out;
}, {});

console.log(byMonthByPrio);

  • Related