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

Handling responses from http requests in Node.js

Below is the code snippet I am working with: exports.post = function(request, response) { var httpRequest = require('request'); var uri = "url.."; httpRequest(uri, function(err, responseHeaders, bodyResponse) { var data = JSON.parse( ...

Getting an Angular TypeError after upgrading to version 9? It seems that the property 'selectors' cannot be read from null

After upgrading my Angular app from v7 to v8 and then v8 to v9, I encountered an issue. My app works perfectly locally when I run ng serve, but when I build for production using ng build --prod and deploy the app, I get an error in the application's c ...

Export an array of objects using the ExcelService module

I am working with an array named listTutors that looks like this: listTutors = [{ countryId: 'tt', gender: 'both', levelId: 'tg', sessionType: 'inPerson', dashboardStatus: ['notPublished', 'p ...

Executing the cucumberjs + playwright tests after starting the angular app using the ng serve command

Our testing process involves using cucumberjs and playwright. Is it possible to initiate Angular with ng serve (using test configuration) before running our tests, and then close the application once the tests are complete? Similar to configuring a web s ...

The ReactJS input box is stubbornly rejecting all input

Struggling with this code and can't seem to figure out why the input lines aren't accepting anything. After searching extensively, I decided it was time to ask for help. P.S. I am new to react class App extends React.Component { state = { inp ...

What is the reason for the lack of variable assignment within the forEach method in Angular?

I am struggling with assigning a value to the variable "this.qdDias" and returning it. After using subscribe, I am unable to retrieve the value at the end of the method. Despite seeing the value in the console.log(this.qdDias), it becomes undefined when re ...

Selecting middleware to be executed based on Express JS request parameters

Can someone please advise me on how to select between two distinct middleware functions, based on the request for a specific endpoint? It may involve something along these lines: router.post("/findAvailableAgents", chooseMiddleware(middleware1, ...

Arranging items by their total sum of arrays in React.js

I'm working with data.js where I have stored my JSON information. Here's a snippet: [ { name: 'Adam Doe', city: 'New York', mark: [8,10,10,10] }, { name: 'Catlyn Stronk', ...

Disabling an Angular MSal route guard based on the environment variable's condition

My routing module is set up with MsalGuard to require authentication for child routes. While this works, I want to disable MsalGuard based on an environment variable when testing locally. How can I achieve this? I attempted using canDeactivate on my rout ...

Enhancing Typography in Material UI with Custom Breakpoints in React CustomThemes

Currently, I am utilizing material UI and React to develop a single-page application (SPA). However, I have encountered an issue with ensuring that my pages are responsive for smaller screen sizes. To address this, I have been manually adding fontSize: { x ...

Lack of code completion in Nuxt options API when using typescript

After setting up Nuxtjs with typescript, I noticed that there are no code completions in the template and script as expected based on the title. Here is the code: <script lang="ts"> import Vue from 'vue'; import { FeaturedJobs } ...

Retrieve form input from a servlet using a name attribute such as "input[]"

Looking to retrieve input values from a form on my JSP page where each input shares the same name. Take a look at this JSFiddle Any suggestions on how I can access these inputs from my servlet? I attempted using String[] description = request.getParamete ...

Acquire the URL using Angular within a local environment

I am currently working on a basic Angular project where I have a JSON file containing some data. [{ "name": "Little Collins", "area": "Bronx", "city": "New York", "coverImage": "https://images.unsplash.com/photo-1576808597967-93bd9aaa6bae?ixlib=rb-1.2.1&a ...

Transform various tables enclosed in separate div elements into sortable and filterable tables

I'm encountering an issue with making multiple tables sortable and searchable on one page. Despite all the tables having the same class and ID, only the first table is responsive to sorting and searching. I've followed a tutorial that recommends ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

Issue with retrieving the positions of two numbers in an array

I encountered a challenge: I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Thi ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

What steps can I take to ensure the reset button in JavaScript functions properly?

Look at this code snippet: let animalSound = document.getElementById("animalSound"); Reset button functionality: let resetButton = document.querySelector("#reset"); When the reset button is clicked, my console displays null: resetButton.addEvent ...

Executing multiple requests simultaneously with varying identifiers following a waiting period

I am looking to send a GET request using the user_id key retrieved from the userData object. This is how the request should be structured: Let's assume we have userData defined as follows: var userData = [ { id: 1, user_id: ...

A guide on verifying if two arrays of integers are permutations using JavaScript

Is there a way to determine if two sets of integers in JavaScript are permutations? For example, given the arrays: a = [1, 2, 3, 4, 5] and b = [2, 3, 5, 1, 4] I want a function that will return true if they are permutations of each other. ...