如何在JavaScript中按月份分组统计并筛选高频家电数据?
家电数据按月分组统计的JavaScript实现方案
需求说明
给定如下家电数据数组:
const appliances = [ { "appliancesType": "Oven", "createdAt": "2022-09-06" }, { "appliancesType": "Oven", "createdAt": "2022-11-27" }, { "appliancesType": "Television", "createdAt": "2022-07-03" }, { "appliancesType": "Television", "createdAt": "2022-07-03" }, { "appliancesType": "Oven", "createdAt": "2022-09-26" } ];
需按createdAt的年月分组,统计每组内出现次数最多的appliancesType,最终每月返回一条包含家电类型、对应日期(取该类型在当月的最后一条记录日期)及数量的结果,预期输出如下:
[ { "appliancesType": "Television", "createdAt": "2022-07-03", "count": 2 }, { "appliancesType": "Oven", "createdAt": "2022-09-26", "count": 2 }, { "appliancesType": "Oven", "createdAt": "2022-11-27", "count": 1 } ]
实现代码
// 1. 按年月分组,同步统计各家电类型的出现次数及最新日期 const monthlyStats = appliances.reduce((acc, item) => { const yearMonth = item.createdAt.slice(0, 7); if (!acc[yearMonth]) acc[yearMonth] = {}; // 初始化当前类型的统计项 if (!acc[yearMonth][item.appliancesType]) { acc[yearMonth][item.appliancesType] = { count: 0, latestDate: item.createdAt }; } // 更新计数 acc[yearMonth][item.appliancesType].count++; // 更新最新日期(ISO格式字符串可直接比较大小) if (item.createdAt > acc[yearMonth][item.appliancesType].latestDate) { acc[yearMonth][item.appliancesType].latestDate = item.createdAt; } return acc; }, {}); // 2. 筛选每个月份的top类型 const result = Object.entries(monthlyStats).map(([_, typeStats]) => { // 按计数降序排序,计数相同时取日期最新的类型 const sortedTypes = Object.entries(typeStats).sort((a, b) => { if (b[1].count !== a[1].count) return b[1].count - a[1].count; return b[1].latestDate.localeCompare(a[1].latestDate); }); // 构造结果对象 const topType = sortedTypes[0]; return { appliancesType: topType[0], createdAt: topType[1].latestDate, count: topType[1].count }; }); // 3. 按年月升序排列结果 const sortedResult = result.sort((a, b) => a.createdAt.slice(0,7).localeCompare(b.createdAt.slice(0,7))); console.log(sortedResult);
代码说明
- 分组统计:通过
reduce方法遍历原始数据,以年月为键分组,同时记录每个家电类型在当月的出现次数和最新记录日期。 - 筛选Top类型:对每个年月分组内的类型统计数据排序,优先按计数降序,计数相同时按日期降序,取排名第一的类型构造结果。
- 结果排序:最后按年月升序排列输出结果,保证时间逻辑的一致性。
内容的提问来源于stack exchange,提问作者Megane
相关产品推荐
相关产品推荐

