Invictus Invictus - 5 months ago 7
jQuery Question

How to sort data hourwise?

I have an array of objects of this type

Obj = { timeEnd:"06:45 AM",
timeStart:"04:23 AM"
}


Array is of type [obj1,obj2, ....] of particular day.

This array defines that how much time is spend on activities.

I want to recreate or transform this array into time wise array like

obj = { '4-5 AM' : 37,
'5-6 AM' : 60,
'6-7 AM' : 45
}


I have tried to search could not help. I am a noob.

Please let me know if you need any other info. Ultimate goal is to create a hourwise chart.js graph

Answer

You could split the 24 h values and count until the target hour is reached and then get the rest of the minutes to add.

function getHourParts(object) {

    function getKey(h) {
       return h + '-' + (h + 1);
    }

    function getTime(s) {
        var t = s.split(':').map(Number);
        return { h: t[0], m: t[1] };
    }

    var result = {},
        start = getTime(object.timeStart),
        end = getTime(object.timeEnd);

    while (start.h < end.h) {
        result[getKey(start.h)] = 60 - start.m;
        ++start.h;
        start.m = 0;
    }
    result[getKey(end.h)] = end.m - start.m;
    return result;
}

console.log(getHourParts({ timeStart: '04:23', timeEnd: '06:45' }));
console.log(getHourParts({ timeStart: '12:03', timeEnd: '12:05' }));