Here is an array of objects that I am working with:
{x: "14:33", y: 0}
{x: "14:34", y: 0}
{x: "14:35", y: 1}
{x: "14:36", y: 1}
{x: "14:37", y: 0}
{x: "15:33", y: 0}
{x: "15:34", y: 0}
{x: "15:35", y: 1}
{x: "15:36", y: 1}
{x: "15:37", y: 0}
Let's consider 4: {x: "15:37", y: 0}
as the last element.
Question: How can we fill this array to cover the past 24 hours, with values like {x: "*hr*:*mm*", y: 0}
)?
For example, the first element should be {x: "15:37", y: 0}
(representing 24 hours ago).
The initial array covers a few hours of time and may have skipped hours or minutes that also need filling.
Update: This is my current solution for filling up the past 24 hours, but it may seem messy:
someFunc() {
const timeArr = this.get24hrTimeArray(this.data[this.data.length - 1].x);
this.fill24Hr(timeArr, this.data)
}
get24hrTimeArray(lastTime) {
let arr = [];
let hours = [];
const endHr: number = +lastTime.split(':')[0];
const endMin: number = +lastTime.split(':')[1];
let hr = endHr;
for (let i = 0; i < 23; i++) {
if (hr > 23) {
hr = 0;
}
hours.push(hr);
hr = hr + 1;
}
hours.push(endHr)
for (let i = 0; i < hours.length; i++) {
let start = 0;
let stop = 60;
if (hours[i] === endHr && i === 0) {
start = endMin;
} else if (hours[i] === endHr && i !== 0) {
stop = endMin + 1;
}
for (let j = start; j < stop; j++) {
if (j < 10) {
arr.push(`${hours[i]}:0${j}`);
} else {
arr.push(`${hours[i]}:${j}`);
}
}
}
return arr;
}
fill24Hr(timeArr, objArr) {
return timeArr.map(time => {
const found = objArr.find(e => e.x === time);
if (found) {
return ({ x: time, y: found.y });
} else {
return ({ x: time, y: 0 });
}
});
}