Home > Mobile >  How to create an array of objects for each date in a date range in JS using a factory function
How to create an array of objects for each date in a date range in JS using a factory function

Time:01-30

I'm trying to create an array of objects for each date in a date range in JS using a factory function.

I'm almost there, but the start value never changes in the resulting array. The only way that I could get it to work is to wrap it inside another new Date().

This is what I have so far:

const myDataPoints = [];

function datapointFactory(start, end, value) {
  return {start, end, value};
}

const startDate = new Date(2023, 0, 1);
const endDate = new Date(2023, 1, 1);
const timeInterval = 1000 * 60 * 60 * 6;

for (let loopDate = startDate; loopDate < endDate; loopDate.setTime(loopDate.getTime()   timeInterval)){
  const endDatapointDate = new Date(loopDate.getTime()   timeInterval);
  myDataPoints.push(datapointFactory(loopDate, endDatapointDate, 50));
}

CodePudding user response:

You were sending in a reference to the same Date object on every iteration, which was simply added to the returned datapoint. You can copy the date either inside the function, or before sending in the argument.

Option 1:

function datapointFactory(start, end, value) {
  return {start: new Date(start), end: new Date(end), value};
}

Option 2:

datapointFactory(new Date(loopDate), new Date(endDatapointDate), 50)

const myDataPoints = [];

function datapointFactory(start, end, value) {
  return {start: new Date(start), end: new Date(end), value};
}

const startDate = new Date(2023, 0, 1);
const endDate = new Date(2023, 1, 1);
const timeInterval = 1000 * 60 * 60 * 6;

for (let loopDate = startDate; loopDate < endDate; loopDate.setTime(loopDate.getTime()   timeInterval)){
  const endDatapointDate = new Date(loopDate.getTime()   timeInterval);
  myDataPoints.push(datapointFactory(loopDate, endDatapointDate, 50));
}

console.log(myDataPoints);

CodePudding user response:

This is because you were giving the same date every time. Instead of this use new start and end date so that it can work properly.Try this changes in your function.

function datapointFactory(start, end, value) 
{
return {start: new Date(start), end: new Date(end), value};
}
  • Related