Home > Mobile >  Render last 12 months for data template
Render last 12 months for data template

Time:11-17

I'm struggling with creating correct data template for my chart. I want it to create template for last 12 months with actual month. For example if I want to have last 12 months i should have data template looking like this:

[{id: BAD,
data: [
{
x: "11",
y: 0
},
{
x: "12",
y: 0
},
{
x: "1",
y: 0
},
...
]},
{id: GOOD,
data: [
{
x: "11",
y: 0
},
{
x: "12",
y: 0
},
{
x: "1",
y: 0
},
...
]},
... 
]

It is not that simple because I don't know what to do when month increases to 12 because then its just keeps increasing value of "x" which stands for month and thus I don't know how should I implement that.

What i tried to do was just this. I have no other clues how to get this any hints how I can get that?

const NUMBER_OF_MONTHS = 12;


const getFirstMonth = (date, numOfMonths) => {
   date.setMonth(date.getMonth() - numOfMonths);

    return date.getMonth();
}


const createDataTemplate = () => {
    const template = [];
    const firstMonth = getFirstMonth(new Date(), NUMBER_OF_MONTHS)

    for (let i = 0; i < RATINGS.length; i  ) {
        template.push({
            'id': RATINGS[i],
            'data': []
        })
        for (let j = 1; j <= NUMBER_OF_MONTHS; j  ) {
            template[i].data.push({
                'x': `${firstMonth   j}`,
                'y': 0
            })
        }
    }

    return template;
}

CodePudding user response:

I solved it like this, generating an array of the next 12 months/year. Which you can then use to loop over and add to you data

const NUMBER_OF_MONTHS = 12;

const getNextTwelveMonths = () => {
  const currentMonth = new Date().getMonth();
  // create array with the months until the currentMonth
  const months = new Array(currentMonth).fill(null).map((_, i) => i   1);

  // add the last x months to the begin of the array
  for (let i = NUMBER_OF_MONTHS; i > currentMonth; i--) {
    months.unshift(i);
  }

  return months;
};
const createDataTemplate = () => {
  const template = [];

  for (let i = 0; i < RATINGS.length; i  ) {
    template.push({
      id: RATINGS[i],
      data: [],
    });
    const nextMonths = getNextTwelveMonths();
    for (let j = 0; j < nextMonths.length; j  ) {
      template[i].data.push({
        x: `${nextMonths[j]}`,
        y: 0,
      });
    }
  }

  return template;
};
  • Related