1

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.

2
  • You have a certain year which you want to start with ? Commented Sep 30, 2020 at 14:25
  • now - 4 years..... Commented Sep 30, 2020 at 14:25

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Do not access Object.prototype method 'hasOwnProperty' from target object
Have you declared it as an object ?
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.