Break Javascript array of timestamps into smaller arrays by hour, day

710 Views Asked by At

I have an array of objects each containing an ID and timestamp like so:

var data = [
{
   id: 1,
   date: '2015-01-01T00:00:00Z'
},
{
   id: 2,
   date: '2015-01-03T03:00:00Z'
},
{
   id: 3,
   date: '2015-01-03T09:00:00Z'
},
{
   id: 4,
   date: '2015-01-05T00:00:00Z'
},
]

I want to chart the quantity of these objects by hour and day. So I need to know how many have a timestamp between 00:00 and 01:00, 01:00 and 02:00, etc. Likewise, I need to find how many have a timestamp between 2015-01-03 and 2015-01-04, etc.

My first instinct is to loop over the hours of the day/days of the week and within that, loop again over the rows in the table and

if (val.date() >> hourIterator && val.date() << (hourIterator + 1)) {
    new_array.push(val)
}

Am I going about this the right way?

2

There are 2 best solutions below

0
Gary Liu On

JavaScript date instance have a function .getTime() to get number of milliseconds, for more http://www.w3schools.com/jsref/jsref_gettime.asp

0
RobG On

Generally it's best to deal with dates as Date objects, however you can get by with treating them as strings in some cases.

The following counts particular parts within a range (inclusive of the limit), but considers only one factor:

var data = [
            {id: 1, date: '2015-01-01T00:00:00Z'},
            {id: 2, date: '2015-01-03T03:00:00Z'},
            {id: 3, date: '2015-01-03T09:00:00Z'},
            {id: 4, date: '2015-01-05T00:00:00Z'},
           ];

/*  @param {string} part        - name of part to compare, e.g. 'day', 'hour'
**  @param {string/number} low  - value for start of range
**  @param {string/number} high - value for end of range
**  @returns {number}           - count of values in range, inclusive
*/
function countInRange(part, low, high) {
  var partNames = {year:0, month:1, day:2, hour:3, min:4, sec:5};
  var n = partNames[part];
  var count = 0;
  data.forEach(function(obj) {
    var b = obj.date.split(/\D/);
    if (b[n] >= low && b[n] <= high) {
      count++;
    }
  });
  return count;
}

console.log(countInRange('day',1,2));   // 1
console.log(countInRange('day',1,3));   // 3
console.log(countInRange('day',4,6));   // 1
console.log(countInRange('min',0,10));  // 4

If you want to consider other factors (e.g. between 02:00 and 06:00 on a particular day or date range) then converting them to Dates may be more suitable.