sort through list of objects based on dates

I need assistance with fetching and organizing data from the provided array of objects. I want to create two separate arrays based on the following criteria:

  1. The first array should only include objects with a date in the current month.

  2. The second array should contain objects from the past 7 days.

Any advice on working with dates would be greatly appreciated as it's not my strong suit.

{
    "status": "success",
    "results": 10,
    "orders": [
        {
            "orderID": 1,
            "orderStatus": 1,
            "purAmt": 1000,
            "orderDate": "2020-06-14T03:23:20.000Z",
            "fullName": "velocity",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="255340494a464c515c654248444c490b464a48">[email protected]</a>",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 1,
                    "name": "lassi",
                    "price": 62,
                    "image": "images\\rtoRAOwj4-conn.PNG",
                    "quantity": 5
                },
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 9
                }
            ]
        },
        // Multiple order objects follow...
    ]
}

Answer №1

If you need to retrieve orders for the current month, utilizing the Date object is key. You can achieve this by implementing the following code snippet:

orders.filter(order => {
  const orderDate = new Date(order.orderDate);
  const today = new Date();
  const isThisYear = orderDate.getFullYear() === today.getFullYear()
  const isThisMonth = orderDate.getMonth() === today.getMonth();

  return isThisYear && isThisMonth;
})

For accessing orders within the last 7 days, consider using the code below:

orders.filter(order => {
  const orderDate = Date.parse(order.orderDate); // in milliseconds
  const today = Date.now(); // in milliseconds
  const millisecondsInAWeek = 604800000;

  return orderDate > today - millisecondsInAWeek;
})

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

What is the best way to remove a key from an object?

let updatedData = {biddate: new Date(), productId: id, bidamount: bid, username: user.displayName, email: user.email}; delete updatedData.key; }; I am looking to remove a specific key from the 'updatedData' object. ...

Submit a form containing multiple input fields along with JavaScript variables

I have successfully posted my form via ajax to PHP and retrieved values from inputs. Now, I would like to include a JavaScript variable in the ajax post as well. Here is the FORM section: <form action="new_alias.php" method="post" id="theForm"> ...

Is there a way to print the entire Bootstrap modal even if the content in the modal body is scrolled beyond visibility?

An issue arises when a user needs to scroll down to see all of the content in the modal body. When printing the modal, only the visible part is printed rather than the entire content. Various code snippets from different sources have been tried with no suc ...

Deactivate a span in real-time using ng-model

I found a helpful guide on creating a custom editable <span> using ngModelController here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#example Now, I am looking to implement a feature that allows me to dynamically disable editin ...

Guidelines for returning a class type within a method in Java

In the searchBook method, I have implemented a way to find a book based on its ISBN number and display it. However, I currently have the return type set as void for this method because I am unsure of how to properly return a "Book" object. How can I modi ...

Navigating Within Pages Upon Component Re-Render in ReactJS/Gatsby

Elaborate on the Issue Currently, while developing a simple ReactJS/Gatsby website, I encountered a problem with one of my functional styled components. After it re-renders, the window abruptly scrolls, causing an unpleasant jumping effect. This issue ar ...

Is there a way to save a Vue file as a PDF in Vue.js?

I am looking for a way to enable users to download a Vue file as a PDF when they click on a button in the main component. Any suggestions on how to achieve this would be greatly appreciated. download.vue <template> <div> This file contai ...

What is preventing me from adding elements to the Generic List using the indexer?

Today, I encountered a peculiar situation that puzzled me: I have a generic list and I attempted to add items to it using its indexer in the following manner: List<string> myList = new List<string>(10); myList[0] = "bla bla bla..."; However, ...

Error message: "Despite using the 'use client' function in Next.js, a ReferenceError occurs as 'window' is undefined."

What is the reason for the server running this hook when "use client" is included? It does not lead to any application crashes, everything functions with no errors, but an error is logged at the const [windowWidth, setWindowWidth] = useState(window.innerWi ...

Steps for integrating an Angular 2 App into Express.js as a view

I am currently working on developing an Angular 2 app that requires data from a script running on the server. To achieve this, I am attempting to integrate my existing Angular app as a view within an express application, similar to the process demonstrated ...

Developing interconnected dynamic components in Angular

Can you help me figure out how to create nested dynamic components while maintaining the parent-child relationship? For instance, if I have data structured like this: - A --A.1 --A.2 -B --B.1 -C I want to build components that reflect this structure, su ...

Error: Attempted to split a non-splitable object

When I wrote a piece of code and tested it in my editor, everything seemed to be working fine. However, upon uploading it to codewars, an error with the following message popped up: "TypeError: n.split is not a function." I attempted to use "n.toString()" ...

`Active the button once user checks one or more checkboxes using AngularJS`

I'm working on a project where I have checkboxes and a button. I need to figure out how to activate the button when one or more checkboxes are checked using AngularJS. Can anyone provide some guidance? <script src="https://ajax.googleapis.com/aj ...

Manipulate data within multidimensional array by adding or requesting values

I have created a multidimensional array in the following way: var languageArray = {}; $('#language li a img').each(function(index) { var helperArray = []; helperArray.push(langi); helperArray.push(getnumber); languageArray.push(h ...

A guide to handling a dynamic form with vue.js

Currently, I am working on implementing a filter option on my website where the options are dynamically loaded from the database. Due to this dynamic nature of the options, using a typical v-model approach seems challenging. The filter includes various pa ...

How can I adjust the width of td based on the content they contain?

Is it possible to dynamically set the width of a <td> in a table to match the size of the largest <td> in that column while still ensuring the table remains at 100% width? Occasionally, my table doesn't reach 100% width due to empty colum ...

Creating intricate JavaScript objects for JSON API integration can be accomplished by following these steps:

Here is a sample JSON structure used for querying an API: "order_items": [ { "menu_item_id": "VD1PIEBIIG", "menu_item_name": "Create Your Own", "modifiers": [ { "modifier_id ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

Exploring the World of Two-Dimensional Arrays in C++

Exploring a basic approach to chunk loading using two-dimensional arrays and PNG images. I'm curious about creating an uninitialized array like this: Chunk[][] chunks; and then initializing it based on the size of the PNG image, assigning different ...

Issue with JQuery executing PHP in Chrome extension

I have been attempting to retrieve the PHP result after using JQuery's post method within the context of a chrome extension. Unfortunately, all I am seeing is the unprocessed PHP code. Below is how I am calling the post method : $.post(chrome.extens ...