Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this:

const events: Array<{year: number, month: number, date: number}> = [
 {year: 2020, month: 10, date: 13},
 {year: 2021: month: 3, date: 12},
 {year: 2021: month: 9, date: 6},
 {year: 2021: month 11, date 23},
]

If I specify a starting point of January 10th, 2021 within the array, how can I create a function that will return all dates from that starting point onward?

Answer №1

If you find yourself needing specific items, consider utilizing the filter method of Array.prototype to isolate them.

When creating a comparison function, I recommend converting each item into a Date Object. This allows for easier comparison by milliseconds, helping identify items that fall after your desired date.

Answer №2

Along with Fabio's response, here is a way to achieve the desired outcome:

function getFilteredDates(datesList: any, startDate: Date) {
    return datesList.filter(item => item.year >= startDate.getYear() && item.month >= startDate.getMonth() && item.date >= startDate.getDate())
}

getFilteredDates(arrayOfDates, new Date(2021, 0, 10)) // yields three arrays

This code assumes that months in JavaScript Date class are indexed starting from 0.

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 method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

Looping through an array of JSON objects in Javascript results in finding instances, however, the process records them

Currently, I am executing a script inside a Pug template. The script commences by fetching an array of JSON objects from MongoDB. I then stringify the array (data) and proceed to loop through it in order to access each individual JSON object (doc). Subsequ ...

Cycle through images that are dynamically generated from retrieved data

Although I have a functional solution for this issue, it feels messy and not the ideal way to handle it in Vue. The challenge is fetching data from a backend related to a "Vendor" entity, which includes photos that need to be displayed on the page. The go ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

Typescript's implementation of AngularJs provider

After creating an Angularjs provider in typescript, I found myself wondering if there might be a more efficient way to achieve the same outcome. My current provider serves as an abstraction for a console logger, with the interface primarily designed to s ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Aurelia validation is failing to work properly when the form is already populated with data

Struggling to implement validation on an edit model-view that is data-bound in the activate method of its view-model. The create.ts file works smoothly with similar code, but without the need to load data. Surprisingly, the validation functions correctly ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

How to access a controller function within a recursive directive template in Angular version 1.3?

In my parent directive, I am able to access controller functions using the $parent operator. However, this method does not work in recursive child directives. Here is a shortened example of the issue: // Sample controller code (using controllerAs):--- va ...

Stellar for occasions that don't come around often

Is it worth utilizing a Comet for events that do not require real-time updates, but can have a delay of around 1 minute? Examples could include: updates on Twitter statuses notifications on Facebook While Comet is commonly used in chat applications (suc ...

Troubleshooting Angular modal fade not functioning

I am facing an issue while trying to display a component called "Login", which belongs to the class "modal fade", from another component named "navbar". Despite my attempts to trigger it by calling data-bs-toggle="modal" data-bs-target="#LoginModal" from t ...

Is it possible for a draggable position:absolute div to shrink once it reaches the edge of a position:relative div

I am facing an issue with draggable divs that have position:absolute set inside a position:relative parent div. The problem occurs when I drag the divs to the edge of the parent container, causing them to shrink in size. I need the draggable divs to mainta ...

The fs.fsync(fd, callback) function in the node.js API allows you

Can you explain the purpose of fs.fsync(fd, callback) in the Node.js API? fs.fsync(fd, callback) This function is used for asynchronous fsync(2). The completion callback only returns an exception if there is one. fs.fsyncSync(fd) This function is for ...

Retrieve client-side environment variables

When making multiple API calls within my components using the fetch method, I found myself constantly having to determine which environment I was in. To streamline this logic, I created a Utils class that provides the appropriate base URL: export default c ...

Angular Service Worker enhancements across various domains

Scenario Our team is currently developing an Angular application that is accessible through multiple domains. Depending on the domain, the app will display different colors and content, but it is essentially the same Angular application. To enhance perfo ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...

Limiting the Rate of Requests to a TCP Server using net.Server

I've been utilizing net.Server as my TCP server. Is there a way to impose a message rate limit? I managed to find solutions for enforcing rate limits in Express (express-rate-limit) and Websocket (websocket-rate-limit), but nothing specifically for ...

Stop the promise chain when the first error callback is encountered

Here is a sequence of promises I am dealing with: Transaction.findPublic({}).then(function(transactions) { combined = combined.concat(transactions); return JoinEvent.find().exec(); }, function(err) { return res.status(503).send(er ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...