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

Utilizing jQuery for serializing unorganized lists

I have created multiple lists within a list and I need to pass the IDs using jQuery to another PHP file (updateDB.php). I attempted to serialize the list data but was unsuccessful. I'm not certain if I have implemented it correctly, I searched extens ...

Update the website's navigation key for improved user experience

Can the navigation key on a website be altered from 'Tab' to another key, such as 'Enter', allowing for the focus to shift to the next element with the corresponding 'tabindex' when the 'Enter' key is pressed? ...

Tips for displaying field options after typing parentheses in TypeScript in Visual Studio Code

Whenever the letter "b" is typed, the suggestion of "bar" appears. However, I would prefer if the suggestions show up immediately after typing the brackets. https://i.stack.imgur.com/OFTO4.png ...

Encountering the error message 'Object is of type unknown' when implementing the createAsyncThunk function post utilization of Typescript and Redux Toolkit

Currently, I am utilizing Typescript in my React application where Redux Toolkit is being used for state management. The data is being fetched from an Express Api and everything operates smoothly if Redux is implemented without Typescript. However, when in ...

Ensuring Data Consistency: Using TypeScript to Strongly Type Arrays with Mixed Variable Types

I have a JSON array that may contain objects of two types, defined by IPerson and ICompany. [ { "Name" : "Bob", "Age" : 50, "Address": "New Jersey"}, { "Name" : "AB ...

Issue with JavaScript code for Google Maps API not functioning as expected

Can someone help me troubleshoot why my simple Google Maps setup isn't working? Thanks! HTML <script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBy2rXc1YewdnqhPaaEd7H0I4DTV_pc7fo&"> </script> <div id="map"> & ...

Tips for preventing unstyled content flash when updating CSS files dynamically

The following jQuery function is used to replace CSS files: function UpdateTheme(theme) { var links = $("link"); var _t = theme; $.each(links, function (i, link) { var _h = $(link).attr('href'); _updatedHr ...

Utilizing the power of jQuery's `.clone` method to create a new window with fully

I am currently working on a project where I need to duplicate a page while maintaining its functionality, and then display it in a new window. My goal is to only clone a specific portion of the page, but for now I am focusing on replicating the entire page ...

How can we utilize a loop to continuously sum up numbers until we reach a multiple of another number, let's say when the total is divisible by 4?

I am trying to create a function in JavaScript that will detect when a given number is not a multiple of 4. If the number is not a multiple of 4, I want to add numbers incrementally until it reaches the closest multiple of 4. Here’s what I have so far: ...

React: Issue with function not recognizing changes in global variable

When the run button is clicked, it triggers an event. However, clicking on the skip button does not take me to Switch Case 2 as expected. Even though the skip state updates, the function still outputs the old value of skip. const CustomComponent = () => ...

Guide to passing return value to CanDeactivate Guard post closing the mat-dialog in Angular Material Dialog

I have implemented a CanDeactivate Guard to detect unsaved changes in a form. When changes are detected, a confirmation dialog is displayed before allowing the user to leave the page. The Boolean value returned depends on the action taken in the dialog. C ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

The ESLint tool seems to be struggling to detect the package named "@typescript-eslint/eslint-plugin"

Struggling with getting ESLint to function properly on a new Angular project in VS Code. The error message I keep encountering is about failing to load "@typescript-eslint/eslint-plugin". After spending the past 3 hours troubleshooting, I have searched hig ...

Different types of outputs that are suitable for a callback

I am currently developing a small node.js project focused on retrieving search terms from a Twitter feed. Although the search functionality is in place, I am facing difficulties in displaying this data on my webpage. The information I wish to showcase is s ...

Protecting NestJS API for Angular App with Auth0

Currently, I am working on an Angular application that utilizes NestJS as the backend. Authentication is functioning properly in the Angular app, where users can log in to Auth0 and are redirected back to our app seamlessly. The /token call in the network ...

`Creating a functional list.js filter``

I'm having trouble making the List.js filter function work properly. The documentation for List.js is not very helpful for someone new to development. Below is the code I am using: HTML: <div class="col-sm-12" id="lessons"> <input class= ...

Transfering data to Handlebars while rendering a template

Is there a method to pass a variable to a handlebars template during its rendering process? Below is the template in question: <script id="listingTopics" type="text/x-handlebars-template"> {{#each this}} <div class="wrapper_individual_listing ...

What is the best way to organize an array both alphabetically and by the length of its elements?

Imagine I am working with an array like this: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. My goal is to sort it in the following order: aaa, aa, a, bbb, bb, c. this.array= this.array.sort((n1, n2) => ...

What is the significance of `/// <reference types="react-scripts" />` in programming? Are there any other XML-like syntaxes that are commonly used in *.d.ts

When working with normal *.d.ts files (which are definition files for TypeScript), we typically use declare *** export interface *** However, there is also this syntax: /// <reference types="react-scripts" /> This syntax is generated by create- ...

Is javascript or ajax the best choice for updating a database in asp.net mvc?

I need help with updating a row in my database based on a change event from a dropdown list. I am not sure whether to use javascript or ajax for this purpose as I want to avoid page refresh. Any recommendations on which method is best and where I can find ...