使用moment js生成日期和年份数组

Generate an array of dates and year using moment js

我有这个代码:

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

我想要这样的东西:

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

你知道吗?我的功能无法正常工作。

您不能声明这样的数组结构,但您可以使用对象,其中键是年份,值是字符串数组。因此,我会建议这样的代码,如果它不存在,它将创建一个年份键,并用一个空数组初始化它,然后我们可以在其中推送值。

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

我来晚了一点,但这是一个没有 while 循环和条件的解决方案。我不相信你需要时间来做这件事,但我会离开它,因为那正是你所要求的。

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>