Max
Max

Reputation: 335

Counting array elements with specific date in javascript

I have an array of Date() objects in javascript and I want to count the number of events on each day.

Here is an example:

What I have is:

Array [ Date 2014-12-04T10:30:20.000Z, Date 2014-12-05T11:04:58.056Z, Date 2014-12-05T11:04:58.056Z, Date 2014-12-05T11:04:58.056Z ]

What I want is:

Array [{date: '2014-12-04', counts: 1}, {date: '2014-12-05', counts: 3}]

Thanks a lot!

Max

Upvotes: 1

Views: 3330

Answers (3)

shimii
shimii

Reputation: 139

I came across the same issue and found this solution which uses Map() `

calc = (obj) => {
            const orders = []
                 const dates_map = new Map()
             //iterate through all the objects inside the orders array
             orders.forEach(order => {
                 // format and get the date
                 const date = new Date(order.created_at).toLocaleDateString('en-GB')
                 //check if the date key exists in the Map() and save it in a temp
                 const temp = dates_map.get(date) || false
                 // if it does not exist
                 if (temp) {
                     // clone the object
                     const previous = {...temp}
                     // increase counter
                     previous.count += 1
                     dates_map.set(date, previous)
                 }else{
                     //create new object to avoid overwriting
                     const result = {}
                     result.count = 1
                     dates_map.set(date, result)
                 }
             })
             console.log(dates_map)
          }

And this is the output

Output: Map(3) {
  '08/05/2021' => { count: 2 },
  '09/05/2021' => { count: 1 },
  '11/05/2021' => { count: 2,}
}

`

Upvotes: 0

Andy
Andy

Reputation: 63524

You much better off having a simple object with the keys as the date and the value as the count. I've added a simple pad function that prefixes a zero where the number is a single digit as per your output requirements.

function pad(n) {
  return n.toString().length == 1 ? '0' + n : n;
}

function getCount(arr) {
  var obj = {};
  for (var i = 0, l = arr.length; i < l; i++) {
    var thisDate = arr[i];
    var day = pad(thisDate.getDate());
    var month = pad(thisDate.getMonth() + 1);
    var year = thisDate.getFullYear();
    var key = [year, day, month].join('-');
    obj[key] = obj[key] || 0;
    obj[key]++;
  }
  return obj;
}

getCount(arr); // Object { 2014-04-12: 1, 2014-05-12: 3 }

DEMO

Upvotes: 0

deitch
deitch

Reputation: 14581

Basic answer:

var arr = [], // fill it with array with your data
results = {}, rarr = [], i, date;

for (i=0; i<arr.length; i++) {
  // get the date
  date = [arr[i].getFullYear(),arr[i].getMonth(),arr[i].getDate()].join("-");
  results[date] = results[date] || 0;
  results[date]++;
}
// you can always convert it into an array of objects, if you must
for (i in results) {
  if (results.hasOwnProperty(i)) {
     rarr.push({date:i,counts:results[i]});
  }
}

These can be made much easier with lodash functions, and Array.forEach() in ES5

Upvotes: 6

Related Questions