Find items that were recently added in the past three days using TypeScript

Looking for a way to filter an object array of products where each element has a string property called addedDate. The goal is to only include products that were added within the last 3 days.

let now = new Date();
let latestProducts: IProduct[];

latestProducts = this.products.filter(product => {
    new Date(product.addedDate).getDate() >= (now.getDate() - 3)});
   
console.log(latestProducts);

I'm running into an issue where nothing is being filtered from the products list. Can someone offer some guidance on how to fix this? Thanks!

Answer №1

Finally, I have achieved what I was looking for with the code snippet below. It might require some optimization in the future.

      let updatedProducts: IProduct[] = [];           

      for (let product of this.products)
      {
        let dateAddedTime = new Date(product.dateAdded).getTime();
        let currentTime = new Date().getTime();
        if (currentTime - dateAddedTime < 3 * 86400000)
          updatedProducts.push(product);        
      }
      
      console.log(updatedProducts);

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

Acquiring exclusive files from Laravel 8 storage directory using JavaScript

I find myself in a specific situation: Working with a Laravel 8 application. My users upload STL files, which are stored in the storage/app/users/{userid} directory. These STL files are private and not accessible to everyone as they are not located in the ...

Comparison between C++ basic String and Java's equivalent

In both C++ and Java, I have a function that returns a byte array with the same logic. After converting the byte array to a basic string and printing it like this: std::string str(byteArray,byteArray+len) The output is properly displayed. However, when ...

Issue with AngularJS $broadcast not functioning when initializing

In the controller, there is HTML button code that attempts to call a specific function on click: <button ng-click="vm.openpopup()" ng-if="!vm.data.length" uib-tooltip="Add Business Value Chain" class="btn btn-default `enter code h ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

Setting the current date of a jQuery datepicker to the value of an input tag

I am looking to assign a value to an input tag that has a datepicker attached to it. Upon initialization of the datepicker, I want to set this value. Below is a hypothetical example of what I am trying to achieve: HTML: <input id="test" value="">&l ...

Create a Div that smoothly transitions in and out, periodically appearing and disappearing

Can anyone assist me in implementing a feature where a message (div) displays on my website for two minutes every 15 minutes? Any advice or script would be greatly appreciated. Thank you in advance! ...

Struggling to eliminate buttons upon clicking, but they persistently reappear (JavaScript, HTML)

I have encountered an issue with buttons in my table that I am struggling to resolve. Each row in the table contains a "Pack" action button, which when clicked, is removed to prevent accidental double-packing of items. Everything was functioning smoothly ...

Having a Jquery resizing problem? No worries! When the width is less than 768, simply enable the click option. And when the width is

HTML <div class="profile"> <a href="#" class="hoverdropdown" onclick="return false;">Profile</a> <ul class="dropdown" style="display: none;"> <li><a href="#">Dashboard&l ...

What causes userAgent to be undefined within _app.tsx during the use of getInitialProps?

When I check the code below, I'm encountering userAgent being retrieved as undefined: const userAgent = context.req?.headers['user-agent'] ?? ''; The issue persists with isMobile, where it's also being returned as undefined a ...

Is it more beneficial to reference JavaScript libraries in individual user controls or in the master page when constructing a website?

Which of the following scenarios is most effective in terms of client-side (JavaScript) library referencing and loading? Assuming that the web solution is well-designed with components properly encapsulated Just to clarify, the master page mentioned coul ...

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

Error in Typescript: The property 'a' is not defined in the type 'A'

Here is an example of the different types I am working with: type Place = { address: string } type Location = { latLng: string } type User = { name: string } & (Place | Location) When attempting to parse the data using this structure, I enco ...

An issue has occurred with attempting to access the 'phone' property of a null value. This error is at the root of the problem and needs to

I have implemented a function to retrieve all clients from an API: this.ws.getallclients().subscribe( client => { this.client = client.map((clients) => { this.filteredOptions = this.addsale.controls['client_id'].valueChanges. ...

Ways to emphasize the index navigation link when on the main page

Currently, there is a web design project that I am tackling and have encountered a slight hiccup that needs resolving. The issue revolves around highlighting different navigation links based on the URL of the current page. This functionality works seamless ...

How can I showcase a timestamp data type element that I fetched from Firestore?

Currently, I am looking to showcase the data stored in my Firestore collection. One crucial element in this collection is the "date" field, which is categorized as timestamp. However, upon attempting to display these values, an error message surfaces: E ...

An effective method for converting a string into a two-dimensional array using JavaScript

One challenge I am facing is checking from a string if a specific fruit has the correct amount on a given date. I've managed to achieve this by converting the string into a 2D array and iterating over the columns. While this method works, I can't ...

The mobile view of the homepage slider is not appearing correctly

.main-slider-img > img{ width: 100%; } .main-slider-content { left: 15%; margin-top: -146px; position: absolute; top: 50%; } .main-slider-content > h2{ line-height: 50px; padding ...

Error: Angular 6 - The 'map' operator is not available on an observable type

After updating to Angular 6, I encountered this error. While I found documentation on using .pipe(), I'm unsure how to implement it when there are multiple .map() functions as shown below. Your assistance would be greatly appreciated... import {In ...

Tips for making an image box with a rollover effect

I need help figuring out how to create a unique user experience within a container that is 500px wide and 800px tall. The container currently has an image as a background, and I want to add a "sign up" button in the middle. When this button is clicked, I w ...

Can you explain the significance of the '#' symbol within the input tag?

I was reading an article about Angular 2 and came across a code snippet that uses <input type='text' #hobby>. This "#" symbol is being used to extract the value typed into the textbox without using ngModal. I am confused about what exactly ...