Tips for showing data from an hour ago in Angular

Here is the code snippet provided:

data = [
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:50:01'
    },
    {
        'name' : 'sample'
        'date' : '2020-02-18 13:20:01'
    },
    // More data entries here...
]

The expected output should be:

 data = [
        {
            'name' : 'sample'
            'date' : '2020-02-18 13:50:01'
        },
        {
            'name' : 'sample'
            'date' : '2020-02-18 12:50:01'
        },
        // Other filtered entries here...
    ]

The goal is to display the data per hour, filtering out entries that are not exactly an hour ago.

data = [
            {
                'name' : 'sample'
                'date' : '2020-02-18 13:50:01'
            },
            // Other hourly data entries here...
        ]

If the data entry is within the last 30 minutes, it should not be displayed. The focus is on data from exactly an hour ago and per hour increments dynamically based on new incoming data.

Here is a link to the sample code: https://stackblitz.com/edit/angular-dnbses?file=src/app/app.component.ts

Answer №1

If you need to group the data by year, month, day and hour:

const groupedData = data.reduce((accumulator, { name, date }) => {
    let currentDate = new Date(date);
    let dateHour = currentDate.getFullYear() + '/' + currentDate.getMonth()  
        + '/' +  currentDate.getDate()  + '/' +  currentDate.getHours();
    accumulator[dateHour] = accumulator[dateHour] || {name, date};
    return accumulator;
}, {})

Here is an example:

let data = [
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:20:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:12:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 13:13:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 12:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 11:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 07:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:50:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:30:01'
  },
  {
      'name' : 'sample',
      'date' : '2020-02-18 01:20:01'
  },
]

const groupedData = data.reduce((accumulator, { name, date }) => {
  let currentDate = new Date(date);
  let dateHour = currentDate.getFullYear() + '/' + currentDate.getMonth()  + '/' +  currentDate.getDate()  + '/' +  currentDate.getHours();
  accumulator[dateHour] = accumulator[dateHour] || {name, date};
  return accumulator;
}, {})

console.log(Object.values(groupedData));

Answer №2

In my latest coding project, I devised a handy function called

GetDataForHour(dataArray, dateToCompare)
. This function proves to be the solution we need. It sifts through the dataArray and extracts array elements that have dates preceding the dateToCompare, while also matching minutes and seconds.

If you're curious to see it in action, check out this link: https://stackblitz.com/edit/angular-rzzkfq

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

Using Javascript to place a form inside a table

When attempting to add a Form inside a Table, only the input tags are being inserted without the form tag itself. $(function () { var table = document.getElementById("transport"); var row = table.insertRow(0); var cell1 = row.insertCell(0); ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

Extracting <p> elements from a separate HTML file and cycling through them

I successfully created a website using only HTML, JavaScript, and jQuery without any server-side scripting or language. Within my website, I have a simple stream.html page that remains unstyled with no CSS formatting. <html> <head> </head& ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

In Deno, it is possible to confirm that a variable is an instance of a String

I'm having trouble asserting instances of string in Deno: import { assertInstanceOf } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2642405050405e445e59445e">[email protected]</a& ...

Looking to reallocate information, paginate, and sort each time a new row is added to the mat-table

In my application, I have a customized <mat-table> with an implemented addRow() function that adds a new row to the table using default values based on the data type. The challenge I'm facing is that each time a new row is added, I find myself ...

How can you make a Dropdown Box with Javascript?

My current table setup is as follows: <table> <tbody> <tr> <td>List 1</td> <td>List 2</td> <td>List 3</td> <td>....</td> </tr> <tr> <td>This section would be the dropdown ...

Struggling to navigate a nested JSON API using NEXTJS?

I am facing difficulties while trying to extract nested JSON API data in NEXTJS. Specifically, I am struggling with extracting a dictionary within a dictionary from the API file. In the example provided below, I have only been successful in consuming entr ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Converting an array of date strings to a single string in JavaScript

Here is the JSON format I received with dynamic data: {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]} Now, I need to convert this into the following format: range(20180723,20180723) Below is my code snippet : var data:Date[] = {"rang ...

Issue with Kendo dropdown's optionLabel functionality malfunctioning

Check out the Kendo code snippet below for a dropdown control. I'm currently facing an issue where I am trying to display a "Please select" option in the dropdown. This code works perfectly fine for all other dropdowns except for this specific one. T ...

Manipulating nested JSON objects with AngularJS by adding and pushing the data

I am looking at a JSON object structured like this : { "Name": "Shivansh", "RollNo": "1", "Stream": "CSE", "OverallScore": "76", "Semester": [ { "SemesterName": "FY-2012 - 1", "TotalScore": "78.00", ...

Disable javascript when using an iPad

I'm working on a website with parallax scrolling that I don't want to function on iPads. Is there a way to prevent the parallax effect from happening when the site is accessed on an iPad? Any guidance on how to disable parallax scrolling based o ...

Modifications to contenteditable elements result in a change to their IDs

Having some trouble with the behavior of a contenteditable div. The code structure is like this: <div contenteditable="true"> <p id="element-id-1">element-id-1</p> <p id="element-id-2">element-id-2</p> </div> E ...

Trouble communicating between Angular HttpClient POST request and Spring Controller

I'm encountering difficulties while trying to perform a POST request from my Angular frontend service class to the backend Spring controller. Despite my efforts, I am unable to see the log.info message from the controller unless I manually trigger th ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...

Vue.js: Issue with dynamically calculating class property

I am attempting to create a computed class in vue.js 2.0 using the following syntax: <li :class="'str1' calcStarClass(1, p.rtg)"> </li> In my methods section, I have the foll ...

Numerous sections with tabs on the webpage

I am in need of incorporating multiple tabbed sections on a single page, but unfortunately they are currently interconnected. When one tab is clicked, it impacts the others. To see this issue in action, you can visit: https://jsfiddle.net/pxpsvoc6/ This ...

The carousel comes to a halt once it reaches the final slide and does not continue cycling

Currently working on a website project for a client and utilizing Bootstrap to create a carousel feature. I am specifically using Bootstrap 3.0. After searching for a similar issue here, I found two cases that resemble mine but unfortunately have no soluti ...

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...