1

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

2
  • 1
    how is the first array? Is it string or date object? Commented Dec 5, 2014 at 11:14
  • It's a date object, as described in the text Commented Dec 5, 2014 at 13:45

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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,}
}

`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.