IWI
IWI

Reputation: 1608

Javascript functional programming and dynamic values in an Array

I am trying to write a function that grabs the first 14 days (starting today) with momentJS. My function currently looks like

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

I understand that fill is for static values and not dynamic ones, so how would I go about fixing this up so that I have an array that has, ['11/12', '11/13', '11/14', etc...]

I think i need some sort of recursion so that it adds 1 day from the last iteratee, or else i think it'll just keep adding 1 day from today for each iteration

Upvotes: 0

Views: 93

Answers (3)

Maik Lowrey
Maik Lowrey

Reputation: 17566

I hope I understand you right. You will get all days from maybe today +14 days in the future. But I dont understand why you will use fill() methode?

Then that will work for you:

var getDaysArray = function(year, month, day) {
    var date = new Date(year, month, day);  
    var result = [];
    var 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) )

Upvotes: 0

shutsman
shutsman

Reputation: 2510

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 today^

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"]

Upvotes: 2

What you are doing is filling an array with a SINGLE date object, like doing this:

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

moment.add() will not return a new date object, but modify the current date object. What you need is to retrieve a new date object on each map (instead of returning the same date object):

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

And if you want to just retrieve a string, just add a format:

let dateArr = Array(14).fill(moment())
.map((date, index) => {
    return date.clone().add(index, 'days'.format('MM/DD'); // Note the `clone()` so a new object is created.
});

Also note how a index is used to add days dinamically depending on the array position, hence first position will be today (adding 0 days).

Upvotes: 1

Related Questions