Generate an array of dates and year using moment js

Tags: ,



I have this code :

let startDate = moment().subtract(4, 'years');
let endDate = moment().endOf('month');
let months = [];
let month = startDate;

while (month <= endDate) {
    if (months.includes(month.format('YYYY'))) {
        months.push([month.format('YYYY'), month.format('MM/YYYY')]);
    } else {
        months.push(month.format('YYYY'), month.format('MM/YYYY'));
    }
    month = month.clone().add(1, 'months');
}

console.log(months);

I want to get something like :

[
   "2016" : ["09/2016", "10/2016", "11/2016", "12/2016"],
   "2017":  ["01/2017", "02/2017"...],
   "2018":  [....]
]

Have you an idea about that. My function is not working properly.

Answer

You can not declare such array structure, but you could use Object where keys would be years and values would be arrays of strings. Therefore I would propose such code which will create a year key if it does not exist and initialize it with an empty array where we can push values in then.

let startDate = moment().subtract(4, 'years');
let endDate = moment().endOf('month');
let months = {};  // this should be an object
let month = startDate;

while (month <= endDate) {
  // if this year does not exist in our object we initialize it with []
  if (!months.hasOwnProperty(month.format('YYYY'))) {
    months[month.format('YYYY')] = [];
  }

  // we push values to the corresponding array
  months[month.format('YYYY')].push(month.format('MM/YYYY'));
  month = month.clone().add(1, 'months');
}

console.log(months);


Source: stackoverflow