Populate an array of objects with time values up to 24 hours ago

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 });
      }
    });
  }

Answer №1

Would it be possible to iterate through 1440 minutes, starting from the current time, and convert each minute into the format hh:mm? Could this approach potentially solve the issue at hand?

let currentTime = new Date();
let currentMinuteIndex = currentTime.getHours() * 60 + currentTime.getMinutes(); // representing the current minute

const totalMinutes = 1440; // 60 minutes per hour times 24 hours
let resultArray = Array(totalMinutes);
for (let j=0; j<totalMinutes; j++) {
  let tempTimeItem = j + currentMinuteIndex;
  let formattedHours = (~~(tempTimeItem/60)%24).toFixed(0); // ensuring hours are within 0-23 range
  let formattedMinutes = (tempTimeItem%60).toFixed(0); // ensuring minutes are within 0-59 range
  resultArray[j] = {
    x:`${formattedHours.padStart(2,'0')}:${formattedMinutes.padStart(2,'0')}`, // adding leading zeros if required
    y: 0
  }
}

console.log(resultArray);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

View the gathered HTML content in a fresh browser tab

I'm looking to enhance the reporting system on my website by sending an AJAX request with a progress bar. The server will collect the necessary data, convert it into HTML, and then send it back to me. Upon successful completion of the AJAX request, I ...

Locating a specific entry in a custom object array based on a property

Currently working on an Angular 2 app using Typescript and encountering a challenge. There is a service that retrieves an array of questions structured like this: export class Question { constructor(public id: number, public quest ...

Display a React component according to the user's input

Within the first (parent) div, there is an underlined message stating: "This JSX tag's 'children' prop expects a single child of type 'ReactNode', but multiple children were provided.ts(2746)". import A from './components/A&ap ...

Automatically loading a div using jQuery after a delay of 5 seconds

I am working on a feature for my homepage that involves 4 div bars. Right now, I have them set to load upon click, but I would like to adjust it so that the first div loads when the page initially loads, and then each subsequent div loads after a certain t ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

What is the best way to create custom shapes using an array of points in the xyz coordinates system with THREE.JS?

For instance: I have the following points [1,0,2],[2,0,2],[3,2,5] I am looking to create a geometric shape using these points by connecting them. I attempted using THREE.Shape, however it only allows me to construct the shape on the x and y axis. Is there ...

What is the rationale behind jQuery.each not using Array.forEach when it is accessible?

After delving deep into the codebase of the underscore library, I came across an interesting discovery. It seems that _.each relies on an ECMAScript 5 API called Array.forEach whenever it is available: var each = _.each = _.forEach = function(obj, iterato ...

Getting data from an API with authorization in Next.js using axios - a step-by-step guide

click here to view the image user = Cookies.get("user") I'm having trouble accessing this pathway. I stored user data, including the token, using cookies. Please assist me with this issue. ...

Tips for retrieving specific values from drop-down menus that have been incorporated into a dynamically-sized HTML table

How can I retrieve individual values from dropdown menus in HTML? These values are stored in a table of unspecified size and I want to calculate the total price of the selected drinks. Additionally, I need the code to be able to compute the price of any ne ...

Define an object in TypeScript without including a specific field type in the definition

Let's consider a scenario where there is an interface called Book: interface Book { id: number info: { name: string, } } Next, a list named bookList is defined: const bookList: Book[] = [ { id: 1, info: { ...

I'm having trouble with my AngularJS Spinner directive

Check out this simple directive I created to display a spinner on my button while something is happening remotely: http://plnkr.co/edit/rAJ4X7A3iidmqUD2M63A?p=preview Here's the html: <!DOCTYPE html> <html ng-app="app"> <head> ...

Retrieving the scrollTop() property of a specific element within an Iframe

Can you retrieve the scrollTop or offset value of an element within an iFrame? For example: $("iframe").contents(".controlPanel").scrollTop(); Is there another method to achieve this? When I attempt this, I receive a null return value. ...

The value sent from the ajax call did not reach the PHP file as expected

Here's the code I'm working with: HTML and Javascript: function getValues(){ var filter; $.ajax({ type: "POST", url: "myphpfile.PHP?action=sek", data: "id=1", async: false, suc ...

Is there a way to eliminate the bottom padding in a textarea field?

Need help removing the bottom padding in a textarea? Check out this code snippet: $('textarea').css("height", $("textarea").prop("scrollHeight")) textarea { width: 300px; resize: none; margin: 0; padding: 0; } <script src="https://a ...

Executing Cascading Style Sheets (CSS) within JQuery/Javascript

I've been encountering a problem with my website. I have implemented grayscale filters on four different images using CSS by creating an .svg file. Now, I'm looking to disable the grayscale filter and show the original colors whenever a user clic ...

Numerous images with clickable features

Currently, I am in the process of designing a screen that will showcase around 50 toggle buttons to be displayed on a monitor within a building. My goal is to incorporate a variety of images as toggles to ensure they are easily visible and identifiable. I ...

Unable to replicate the functionality of the tab key using jQuery for the enter key

How can I focus on the first input ('Qtd on the table') after pressing enter on the 'Buscar' input? I've tried various solutions like $(this).nextAll('input').first().focus(); $(this).next('input:text').focus ...

What are the advantages of combining the website URL and API URL within the Angular service?

When deploying my application in a production environment, I encounter an issue with the URL addresses. The web address is , while the API address is . However, when making a request to the API through Angular, the URLs get concatenated into . This issue d ...

Is it possible to decode a two-dimensional array of objects in JSON?

My scenario involves a two-dimensional array of objects structured as follows: function test(n){ this.id = n; } var testArray= new Array(2); for(i = 0; i < testArray.length; i++){ testArray[i] = new Array(2); for(j = 0; j < testArray[i].lengt ...

Implementing Object.somefunction() in ngFor with Angular

In my Angular project, I am using an ngFor loop to iterate over keys generated by Object.keys() in the following code snippet: <ul id='nav-tablist' class='tabrows'> <li *ngFor="let tab of obj.keys(tabList)"> ...