GPiter
GPiter

Reputation: 799

Generate an array of dates and year using moment js

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.

Upvotes: 1

Views: 2005

Answers (2)

ray
ray

Reputation: 27245

I'm a little late, but here's a solution with no while loops and no conditionals. I'm not convinced you need moment for this, but I'll leave it since that's specifically what you asked for.

const numYears = 4;
const numMonths = numYears * 12;

const start = moment();

const months = Array.from({length: numMonths}, (_, i) => moment(start.subtract(1, 'months'))).reverse();

const result = months.reduce((acc, m) => {
  const year = m.year();
  acc[year] = acc[year] || [];
  return {
    ...acc,
    [year]: [...acc[year], m.format('YYYY-MM')]
  }
}, {});

console.log(result);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Upvotes: 0

0x1211
0x1211

Reputation: 225

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);

Upvotes: 4

Related Questions