要遍历每日日期的多维数组并按月对它们进行分组,可以使用JavaScript中的Array.prototype.reduce
方法来实现。以下是一个详细的步骤和示例代码:
Date
对象用于表示日期和时间。reduce
方法可以使代码更加简洁和易读。假设我们有一个包含每日日期的多维数组,如下所示:
const dailyDates = [
new Date('2023-01-01'),
new Date('2023-01-02'),
new Date('2023-02-01'),
new Date('2023-02-15'),
new Date('2023-03-10'),
new Date('2023-03-20')
];
我们可以使用以下代码按月对这些日期进行分组:
const groupedByMonth = dailyDates.reduce((acc, date) => {
const yearMonth = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`;
if (!acc[yearMonth]) {
acc[yearMonth] = [];
}
acc[yearMonth].push(date);
return acc;
}, {});
console.log(groupedByMonth);
{
'2023-01': [ Date('2023-01-01'), Date('2023-01-02') ],
'2023-02': [ Date('2023-02-01'), Date('2023-02-15') ],
'2023-03': [ Date('2023-03-10'), Date('2023-03-20') ]
}
reduce
方法的第二个参数是一个空对象{}
,作为初始累加器值。'YYYY-MM'
的字符串作为键。Date
对象。通过上述方法,可以有效地按月对每日日期的多维数组进行分组。
领取专属 10元无门槛券
手把手带您无忧上云