How to sort data hourly?

I have an array of objects of this type

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

The array is of the type [obj1, obj2, ....] of that day.

This array determines how much time is spent on actions.

I want to recreate or transform this array into a temporary wise array like

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

I tried to search could not. I am noob.

Please let me know if you need any other information. The ultimate goal is to create an hourly chart chart.js

+4
source share
4 answers

You can divide the values ​​of 24 hours and count until the target hour is reached, and then add the rest of the minutes.

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' }));
Run code
+3
source

, . Map, Object ( , ) Array.

var durations = [{timeStart: "04:23 AM", timeEnd: "06:45 AM", }, {timeStart: "09:23 AM", timeEnd: "11:30 AM", }, {timeStart: "11:09 PM", timeEnd: "01:19 PM", }];

function getValue(time) {
	var [hour, minute, period] = time.replace(':', ' ').split(' ');
	var date = new Date();
	date.setHours((period === 'PM' ? 12 : 0) + +hour, +minute);
	return date;
}

var result = {};

durations.forEach(duration => {
	var time = getValue(duration.timeStart),
		end = getValue(duration.timeEnd);

	for (var hour = time.getHours(); hour <= end.getHours(); hour++) {
		var endMinute = hour === end.getHours() ? end.getMinutes() : 59,
			minute = 0,
			hourSpan = `${hour}-${hour + 1}`;

		result[hourSpan] = result[hourSpan] || new Map;
		while (minute <= endMinute)
			result[hourSpan].set(minute, minute++);
	}
});
Object.keys(result).forEach(span => {
	result[span] = result[span].size;
});
console.clear();
console.log(result)
+2

The best way to sort any array relative to time is to use the UTC timestamp value. First convert stringValue to a timestamp, and then sort the array according to the timestamp values.

0
source

All Articles