JMA
JMA

Reputation: 994

Group objects in an array per hour in javascript

I have this objects in an array,

var progress = [ 
    {
        "duration" : 120,
        "dateAdded" : "2017-03-02T15:45:31.315Z"
    }, 
    {
        "duration" : 120,
        "dateAdded" : "2017-03-02T15:47:32.150Z"
    },{
        "duration" : 120,
        "dateAdded" : "2017-03-02T12:45:32.150Z"
    },{
        "duration" : 120,
        "dateAdded" : "2017-03-02T12:47:32.150Z"
    },{
        "duration" : 120,
        "dateAdded" : "2017-03-02T10:45:32.150Z"
    }
]

How can I group the objects per hour? I want to have an output of,

var progress = [{duration:340,time:"15:00"},{duration:340,time:"12:00"},{duration:120,time:"10:00"}]

So what happen here is, I added all duration per hour. so for example, in Time 15:00, I have 120 + 120 = 340.

I am going to use the solution for Timeframe.

Upvotes: 1

Views: 2831

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could slice the date for just the part with the date and hour and group it in a hash table.

var progress = [{ duration: 120, dateAdded: "2017-03-02T15:45:31.315Z" }, { duration: 120, dateAdded: "2017-03-02T15:47:32.150Z" }, { duration: 120, dateAdded: "2017-03-02T12:45:32.150Z" }, { duration: 120, dateAdded: "2017-03-02T12:47:32.150Z" }, { duration: 120, dateAdded: "2017-03-02T10:45:32.150Z" }],
  hash = Object.create(null),
  grouped = [];
  
progress.forEach(function (a) {
    var key = a.dateAdded.slice(11, 13);
    if (!hash[key]) {
        hash[key] = { duration: 0, time: key + ':00' };
        grouped.push(hash[key]);
    }
    hash[key].duration += a.duration;
});

grouped.sort(function (a, b) {
    return b.time.localeCompare(a.time);
});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 5

Related Questions