Removing dates that are in the past from an array of objects

How can I filter out objects with a date earlier than today's date? For example, if today is: 2022-08-17 and I have { date: "2022-08-15" } in my array of objects.

let todayDate = new Date().toISOString().slice(0, 10);

let arr = [
  { date: "2022-08-15" }, // todayDate is 2022-08-17 so this object should be removed
  { date: "2022-08-31" },
  { date: "2022-10-19" },
  { date: "2022-10-27" },
];

// expected result after filtering

// let arr = [
//   { date: "2022-08-31" },
//   { date: "2022-10-19" },
//   { date: "2022-10-27" },


Answer №1

To find dates greater than the current date, one approach is to use the Date constructor to parse the date and compare it with the current timestamp:

let arr = [
  { date: "2022-08-15" },
  { date: "2022-08-31" },
  { date: "2022-10-19" },
  { date: "2022-10-27" },
];

const now = Date.now()
const result = arr.filter(e => new Date(e.date) > now)
console.log(result)

Another way to achieve the same result is by comparing the date strings directly based on their lexicographical order:

let todayDate = new Date().toISOString().slice(0, 10);

let arr = [
  { date: "2022-08-15" },
  { date: "2022-08-31" },
  { date: "2022-10-19" },
  { date: "2022-10-27" },
];

const result = arr.filter(e => e.date > todayDate)
console.log(result)

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

Encountering a difficulty in initializing a dynamic integer array in C++, could be a result of a potential

Struggling with the correct syntax to declare dynamic arrays (of type integer) in C++ as a new learner. Here's my current code: #include <iostream> using namespace std; int main() { int* pArray(new int[5]{10,20,30,40,50}); *(pArray + ...

Duplicate request submissions in ExtJs causing inefficiency

Trying to resolve an issue with my ExtJs table that handles remote filtering, sorting, and paging of data on the server. The problem arises when a default request is being sent alongside every other request: localhost/request?page=1&start=0&limit= ...

Setting the Content-Type of a JavaScript file within a NodeJS application

I am facing an issue with opening a js-file on my NodeJS server, as it always specifies the .js file with a Content-Type of "text/html." My objective is to send user-input from an html form to a JavaScript file for performing calculations and later genera ...

Fetch data from an API using JavaScript and load a JSON file

I'm currently facing an issue with this specific problem: I am attempting to retrieve the JSON file from using the following code: $("document").ready(function () { // Triggering function reLoad(); function reLoad() { $.getJSON( ...

Display issue with loading animation

After clicking the button and seeing the alert message, I noticed that the loading animation does not display during the await new Promise(r => setTimeout(r, 2000));. /* script.js */ async function refreshStatus() { document.getElementById("load ...

Unexpected behavior observed with negated character: ? ^

I am looking to create a form where users can input their phone number and have the flexibility to choose how they want to separate the numbers. I have been using a regex pattern for validation: var regex = /[^0-9 \/-\\\(\)\+ ...

Display a single item from the Bootstrap carousel on mobile devices

Seeking help with my Bootstrap Carousel - displaying 2 items on Desktop but wanting to show one item at a time on Mobile. Any solutions? Visit this link for more info HTML Code: <div class="container"> <div id="myCarousel" class="carousel sli ...

Serve static files from a specific directory in Express.js that is not the root path

I am in need of specific files for a particular page <link rel="stylesheet" href="/vendor/css/style.css"> <script type="text/javascript" src="/vendor/js/app.js"></script> I have configured the express static route like this: express = ...

Please provide values in the input box, with each value separated by

I attempted the following code: success: function (result) { for (var i = 0; i < result.d.length; i++) { var emails = new Array(); emails = result.d[i].Emailid; alert(emails); $("#EmailCC").val(emails); ...

Struggling with low frames per second when using antialiasing in a Threejs environment

Enabling antialias on the WebGL renderer causes a significant drop in FPS, going from 60 down to about 25. this.renderer = new THREE.WebGLRenderer({ antialias: true }); This issue seemed to arise after I introduced multiple scenes and had to manually ...

What is the best way to create a smooth transition between multiple cameras or scenes in three.js?

Wondering if it's feasible, and if so, what's the optimal method to create a specific effect in three.js: I have scene S1 being shown from camera C1and want to: transition to scene S2 as seen from camera C2, or transition to scene S1 as viewed ...

Ways to determine if an array with a mix of data types includes string values

Challenge I'm Currently Tackling: To solve this challenge, create a function named "findShortestWordAmongMixedElements". The task is to find and return the shortest string from an array that contains mixed element types. Important Notes: * In c ...

What circumstances result in async methods throwing errors and how can you effectively handle them?

According to the documentation for Node.js: Sometimes, even with asynchronous methods in the Node.js API, exceptions may be thrown using the throw mechanism. To handle such exceptions, you need to use try/catch blocks. There isn't a complete list o ...

What is the best way to update a specific element within a web page?

My current implementation involves utilizing this code snippet within a functional component : return ( <div style={{ height: "700px", overflow: "auto" }}> <InfiniteScroll pageStart={0} loadMore={Fet ...

What is the CoffeeScript alternative for () => { return test() }?

Currently, I am attempting to write this code in CoffeeScript and finding myself at a standstill... this.helpers({ events: () => { return Events.find({}); } }); ...

Personalize the File upload with HTML and Javascript

https://jsfiddle.net/yugxqopz/ I'm new to the world of UI and have a simple request: 1) I want to upload a document using an "attach file" option 2) Once the file is selected, I want to automatically trigger a specific JavaScript function as shown ...

Modify the background color of one div based on the visibility of another div

My carousel consists of three divs representing a Twitter post, a Facebook post, and a LinkedIn post. These are contained within another div called #social-media-feeds. I am curious if it is feasible to adjust the background color of #social-media-feeds d ...

Guidelines for allowing TypeScript to automatically determine the precise structure of data objects in a generic HttpServiceMock through the utilization of TypeScript Generics and Interfaces

I'm currently diving into TypeScript and trying to accomplish something that I'm not entirely sure is possible (but I believe it is). Here's an example of the code I have: interface HttpServiceMockData<T> { status: number; data: T ...

Using Python's for loop to iterate through a two-dimensional index

I'm facing a challenge that seems simple, but I'm struggling to figure out how to tackle it using Python. Within my Python for loop, I have a unique value defined during each iteration. Now, I want to access the value of the NEXT or PREVIOUS uni ...

ajax encountering error but producing correct result

Below is the code snippet for a function: side= 'car'; var request_checkUrl = '/antibot/antibot_data?script=' + side; $.ajax({ url: request_checkUrl, dataType: 'application/json', complete: function(data){ ...