Steps for sorting items from a list within the past 12 hours

I'm currently working with Angular and I have data in JSON format. My goal is to filter out items from the last 12 hours based on the "LastSeen" field of the data starting from the current date and time.

This is a snippet of my data:

{
    "Products": [
        {
            "ProductID": "8",
            "UserName": "User north",
            "Date": "08/22/2018 09:58:09",
        },                      
        {
            "ProductID": "732",
            "UserName": "Ser",
            "Date": "07/30/2020 22:31:26",
        },
        // more data here ...
    ]
}

Any insights on how I can achieve this filtering process?

Answer №1

If you have a JSON data, you can utilize JSON.parse() to convert it into an object and employ Array.prototype.filter() to select specific elements. Additionally, you can make use of Date.prototype.setHours() along with Date.prototype.getHours() for calculating the time limit.

Here are a couple of important points to consider:

  1. Your JSON appears to be missing a comma after the username of ProductID 744 (so I inserted one);
  2. It's crucial to avoid trailing commas in JSON object properties (so I removed them).

var jsonData = `{
    "Products": [
        {
            "ProductID": "8",
            "UserName": "User north",
            "Date": "08/22/2018 09:58:09"
        },                      
        {
            "ProductID": "732",
            "UserName": "Ser",
            "Date": "07/30/2020 22:31:26"
        },
        {
            "ProductID": "733",
            "UserName": "Zte",
            "Date": "07/29/2020 22:53:31"
        },
        {
            "ProductID": "734",
            "UserName": "Rck",
            "Date": "07/30/2020 18:01:04"
        },
        {
            "ProductID": "735",
            "UserName": "TIO",
            "Date": "05/13/2020 18:53:18"
        },
        {
            "ProductID": "736",
            "UserName": "IDO",
            "Date": "07/21/2020 15:51:57"
        },
        {
            "ProductID": "737",
            "UserName": "olp",
            "Date": "07/30/2020 15:21:54"
        },
        {
            "ProductID": "738",
            "UserName": "oku",
            "Date": "07/30/2020 15:24:09"
        },
        {
            "ProductID": "743",
            "UserName": "ijk",
            "Date": "06/16/2020 06:26:30"
        },
        {
            "ProductID": "744",
            "UserName": "ojp",
            "Date": "06/16/2020 20:12:29"
        },
        {
            "ProductID": "746",
            "UserName": "jpi",
            "Date": "06/19/2020 14:05:43"
        },
        {
            "ProductID": "747",
            "UserName": "oom",
            "Date": "06/19/2020 15:30:51"
        },
        {
            "ProductID": "750",
            "UserName": "okn",
            "Date": "06/29/2020 17:59:08"
        }
    ]
}`;

var objData = JSON.parse(jsonData);
    
var currentDate = new Date();
var twelveHoursAgo = new Date(currentDate.setHours(currentDate.getHours() - 12));

var productsWithinLast12Hours = objData.Products.filter(product => new Date(product.Date) >= twelveHoursAgo);

console.log(productsWithinLast12Hours);

Answer №2

This information may be valuable to you!

const records = {
    "Items": [
        {
            "ItemID": "8",
            "Name": "User north",
            "Date": "08/22/2018 09:58:09",
        },                      
        {
            "ItemID": "732",
            "Name": "Ser",
            "Date": "07/30/2020 22:31:26",
        },
        {
            "ItemID": "733",
            "Name": "Zte",
            "Date": "07/29/2020 22:53:31",
        },
        {
            "ItemID": "734",
            "Name": "Rck",
            "Date": "07/30/2020 18:01:04",
        },
        {
            "ItemID": "735",
            "Name": "TIO",
            "Date": "05/13/2020 18:53:18",
        },
        {
            "ItemID": "736",
            "Name": "IDO",
            "Date": "07/21/2020 15:51:57",
        },
        {
            "ItemID": "737",
            "Name": "olp",
            "Date": "07/30/2020 15:21:54",
        },
        {
            "ItemID": "738",
            "Name": "oku",
            "Date": "07/30/2020 15:24:09",
        },
        {
            "ItemID": "743",
            "Name": "ijk",
            "Date": "06/16/2020 06:26:30",
        },
        {
            "ItemID": "744",
            "Name": "ojp",
            "Date": "06/16/2020 20:12:29",
        },
        {
            "ItemID": "746",
            "Name": "jpi",
            "Date": "06/19/2020 14:05:43",
        },
        {
            "ItemID": "747",
            "Name": "oom",
            "Date": "06/19/2020 15:30:51",
        },
        {
            "ItemID": "750",
            "Name": "okn",
            "Date": "06/29/2020 17:59:08",
        }
    ]
};
const currentTime = new Date();
const priorTime = new Date(currentTime.setHours(currentTime.getHours() - 12))
const filteredData = records.Items.filter(item=>(new Date(item.Date))>priorTime)
console.log(filteredData)

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

Differences in SVG rendering between Chrome and Firefox

I am eager to create a diagram on my website using SVG. To ensure the diagram is displayed in full screen, I am utilizing availHeight and availWidth to determine the client screen's height and width, then adjust the scaling accordingly. My current sc ...

Issue: Unable to access GET request with Express and handlebars

Hello everyone, I'm just getting started with JS/Handlebars and I'm facing an issue trying to display an image from my home.hbs file in VS Code. When I start the server, this is the message I receive: Below is the code for my server: const expre ...

The Ant Design form is not updating values after using setFieldsValue in Testing Library

Currently, I am working with the testing-library/react-hooks library and using renderHook. One issue I'm facing is that I am unable to set a value for my antd form using setFieldsValue. It seems like the value is not being set properly. What could be ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

Unable to retrieve context value for authentication requirements

I have implemented a feature in my application where I redirect users to the login page for certain special pages if they are not logged in. The implementation involves using react-router. Here is the code snippet for my RequireAuth component: const Requir ...

Guide on submitting a form via Ajax on a mobile app

Looking for a way to submit the form located in components/com_users/views/login/tmpl/default_login.php using Ajax. <form action="<?php echo JRoute::_('index.php?option=com_users&task=user.login'); ?>" method="post"> <fie ...

The best approach for sending parameters to the parent class in TypeScript for optimal efficiency

What's the optimal solution to this problem? I really appreciate how we can specify attributes in the constructor and TypeScript takes care of handling everything to assign values to the props in JavaScript - like I did with 'department' her ...

Is it possible to adjust the block size for infinite scrolling in Ag-Grid?

Is there a way to adjust the block size in the scenario where the row model is set to "infinite" and a datasource is specified? For instance, when the getRows() function of the datasource is called, is it possible to define the startRow and/or endRow? The ...

How can I display the value entered in a text input field when using ajax upload?

Is there a way to display the value of an input type text when using ajax for file upload? I have successfully implemented code to upload files to a directory called attachments_files, but I am facing an issue. How can I retrieve and echo the value from i ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

Implementing dynamic active class changes in a navbar with JavaScript

My goal was to have the navbar change its class to 'active' dynamically when a user clicks on the <li> tag. Can you help me pinpoint where I made a mistake? dynamicNavbar(); function dynamicNavbar() { $('.nav_w3ls .menu a'). ...

Firebase's equalTo function seems to be malfunctioning

Having encountered an issue with Firebase, I am currently attempting to fetch all of my posts in JavaScript. Specifically, I am looking for posts in the correct language that are marked as "published" and sorted by their published date. In my Firebase dat ...

The ontrack listener for WebRTC peerConnection fails to fire

Primarily, the challenge I'm facing is unique from what I have come across in my research on "google". My setup involves using Spring Boot as a signaling server to establish connections between two different tabs of the browser or utilizing two peerCo ...

Converting a timestamp from PHP in JSON format to date and time using JavaScript

Within the JSON file, there is a timestamp associated with each user login. An example of this timestamp is: timestamp: "1541404800" What steps should be taken to convert this timestamp into date and time format? ...

Error encountered in Next.js when defining columns for a MUI data grid

Currently, I am integrating MUI Data Grid into a Next.js app under development. While attempting to define a more intricate column structure, I encountered an error: { field: 'home_address', valueGetter: (value, row) => { retur ...

What is the optimal method for generating numerous records across various tables using a single API request in a sequelize-node.js-postgres environment?

I need to efficiently store data across multiple separate tables in Postgres within a single API call. While I can make individual calls for each table, I am seeking advice on the best way to handle this. Any tips or suggestions would be greatly appreciate ...

Passing events from a parent component to dynamically created child components in Angular

UPDATE: I've decided to tackle this issue in a different way by retrieving dynamic child component values in the parent component's save() function, following the accepted answer. I am attempting to create a system where a parent component emits ...

What's causing this javascript to malfunction on the browser?

I encountered a problem with the code in my .js file. Here is a snippet of the code: $.extend(KhanUtil, { // This function takes a number and returns its sign customSign: function(num){ num = parseFloat(num) if (num>=0){return 1} ...

Extract branch, path, and URL from the .gitmodules file by utilizing JavaScript Regex

Is there a way to extract branch, path, and URL details from the .gitmodules file using JavaScript Regex? .gitmodules [submodule "PATH"] path = <PATH> url = <URL> [submodule "PATH"] path = <PATH> url = <URL> ...

How can one efficiently update numerous data properties in a Vue.js application?

My information is as follows: data() { return { monday_start: '', monday_end: '', tuesday_start: '', tuesday_end: '', wednesday_start: '', ...