Utilizing JavaScript's functional programming to manipulate dynamic values within an array

Currently, I am working on a function that aims to extract the first 14 consecutive days (starting from today) using momentJS. Here is what my current function looks like:

let dateArr = Array(14).fill(moment())
    .map((date) => {
        return date.add(1, 'days')
    });

I've realized that fill is suitable for static values, not dynamic ones. How can I modify this code so that it generates an array like this:

['11/12', '11/13', '11/14', etc...]

It seems like I may need to implement some form of recursion to ensure that each day is added sequentially based on the previous iteratee, rather than simply adding one day from the present date in every iteration.

Answer №1

Array(14).fill(moment())
    .map((date, i) =>  date.add(1, 'days').format('MM/DD'));

OUTPUT:

(14) ["01/13", "01/14", "01/15", "01/16", "01/17", "01/18", "01/19", "01/20", "01/21", "01/22", "01/23", "01/24", "01/25", "01/26"]

UPDATE:

Start from the current date^

Array(14).fill(moment())
    .map((date, i) =>  {
if(i === 0) {
return date.format('MM/DD')
}
return date.add(1, 'days').format('MM/DD')
});

(14) ["01/12", "01/13", "01/14", "01/15", "01/16", "01/17", "01/18", "01/19", "01/20", "01/21", "01/22", "01/23", "01/24", "01/25"]

Answer №2

Instead of populating an array with a single date object, you can ensure that each element in the array contains a separate date object by following this approach:

let currentDate = moment();
let datesArray = Array(14).fill(currentDate)
.map((date, index) => {
    return currentDate.add(index, 'days').clone();
});

The moment.add() method modifies the existing date object instead of returning a new one. To create new date objects for each element in the array, use the clone() method as shown above.

let datesArray = Array(14).fill(moment())
.map((date, index) => {
    return date.clone().add(index, 'days'); // Ensure a new object is created using `clone()`.
});

If you only require a string representation of the date, you can add a format to retrieve it:

let datesArray = Array(14).fill(moment())
.map((date, index) => {
    return date.clone().add(index, 'days').format('MM/DD'); // Create a new object with `clone()` and format the output.
});

Utilize the index variable dynamically to account for adding days based on the array position, where the first position corresponds to today (adding 0 days).

Answer №3

It seems like you're looking to retrieve a list of dates starting from today and spanning over the next 14 days. However, I'm curious as to why you're considering using the fill() method?

You could achieve your goal with the following code snippet:

const getDaysArray = function(year, month, day) {
    let date = new Date(year, month, day);  
    let result = [];
    let i;
    
    for (i = 0; i < 14; i++) {
        result.push(date.getMonth() + '/' + date.getDate());
        date.setDate(date.getDate() + 1);    
    }
    
    return result;
}    

console.log(getDaysArray(2021, 1, 12));

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

An error was encountered: An identifier that was not expected was found within the AJAX call back function

I am experiencing an issue while attempting to query an API. An Uncaught SyntaxError: Unexpected identifier is being thrown on the success part of my JQuery Ajax function. $(document).ready(function(){ $('#submitYear').click(function(){ let year ...

What is the process for assigning one array to another array in programming?

Check out this code snippet: export default class Application extends EventEmitter { constructor() { super(); this.config = config; this.data = { planets: [planetData] }; this.init(); let url; let count; let plane ...

How can I stop the hover event on a series in Highcharts from triggering a hover event on the nearest point (marker)?

When hovering over the series line on a date-time chart, the default behavior is to trigger the hover event on the nearest point of the series. However, I only want to trigger the hover event on the markers (points), not the series itself. If I use stopP ...

Error: Invalid Syntax Detected in React

I encountered an error that reads as follows: events.js:72 throw er; // Unhandled 'error' event ^ SyntaxError: /vagrant/resources/assets/js/react/react_app.js: Unexpected token (366:10) 364 | var InvestorsTable = React.cr ...

Comparing JSON Objects in Javascript

I'm in the process of developing a web application that retrieves data from a server and displays it to the user. The script pulls data from the server every 10 seconds, and if there's any change in the data, it alerts the user. Currently, the co ...

Error! Element not found in cloned iframe #2460, promise unhandled

Can you help me troubleshoot this issue? This is the code I'm working with: const section = document.createElement("section"); const myHTMLCode = "<p>Greetings</p>"; section.insertAdjacentHTML("afterbegin", my ...

Node JS promise predicaments

I'm stuck trying to figure out why this function is returning before my message array gets updated with the necessary values. var calculateDistance = function (message, cLongitude, cLatitude, cSessionID) { return new Promise(function (resolve, re ...

An error occurred while trying to update with Webpack Dev Server: [HMR] Update failed due to an issue fetching the update manifest,

I encountered an issue in the browser console while attempting to live reload / HMR on Webpack. The error arises after saving a file following a change. [HMR] Update failed: Error: Failed to fetch update manifest Internal Server Error Could the failure b ...

Is it possible to issue commands within JavaFX-hosted Javascript?

I'm currently working on developing a JavaFX Application that assists me in creating JavaScript scripts. The application consists of a raw text Pane on the left, and an HTML Pane on the right which displays the rendered HTML content from the left Pane ...

Dynamically changing the date format within the item-text of v-autocomplete in Vuetify

My current v-autocomplete component is fetching an array of items from GrowthTasks.edges to display. <v-autocomplete label="Start Week" :items="GrowthTasks.edges" item-text="node.growthStartDate" item-value="node.grow ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

What is the best way to exclude the bottom four rows when sorting with MatSort?

Is there a way for me to keep the last four rows fixed when sorting the table based on the column header? Here is an image of the table: table image <table mat-table [dataSource]="dataSourceMD" matSort (matSortChange)="getRowMaximoTable( ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

Is it possible to convert uncontrolled components from class-based to functional components?

I'm having difficulties converting the Uncontrolled Components from class Components into Functional Components... Class Components: import React from 'react'; class NameForm extends React.Component { constructor(props) { super(props ...

How do I determine the appropriate image type to use?

I'm a beginner in the world of Node.js and I'm currently working on an application that stores image files. However, I am unsure about what type of data the images should be. const userSchema = new mongoose.Schema({ userImage: { type ...

Tips for utilizing the simple-peer module within a Node.js environment?

I recently started using Node.js and I'm interested in incorporating the simple-peer module into my application. However, I am struggling to understand how to implement it based on the provided documentation. Are there any resources available that can ...

Navigate to the previous state or refresh the component for two distinct API calls in ReactJS

In order to fetch different data from the API, I have created two separate functions to handle the updates. If a user clicks on the previous menu item (All) after navigating away, the updateLanguage function should be triggered or the component should be ...

Activate audio and trigger notification

I'm looking to incorporate a small beep sound into my web application before displaying an alert message. Here's what I currently have: if(_none_valid) { $.playSound('/static/wav/beep_error.wav').delay(300); alert('ERROR: ...

Filtering an array of JSONs in Vue.js using a separate array of JSONs

In my code, there are two arrays of JSONs: one named products and another called deletedProducts. The task is to filter out the products that are not present in the deletedProducts array. For instance: products = [ { id: 1, name: 'Box&apos ...

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...