重构groupByDate函数:仅返回含非空数组的分组结果
优化groupByDate函数:仅保留非空月份分组并移除初始累加数组
原始数据与代码
待处理数据
const data = [ { date: "2022-11-30T07:33:07.992955008Z", reponame: "test-repo", category: "veggy", }, { date: "2022-11-30T07:33:07.992956372Z", reponame: "veggy-repo", category: "fruit", }, { date: "2022-11-30T07:33:07.992956372Z", reponame: "veggy-repo", category: "veggy", }, { date: "2022-11-30T07:33:07.992956372Z", reponame: "vegy-repo", category: "vegy", }, ];
原始groupByDate函数
const moment = require('moment') const monthsAcc = [{'January':[]}, {'February':[]}, {'March':[]}, {'April':[]}, {'May':[]}, {'June':[]}, {'July':[]}, {'August':[]}, {'September':[]}, {'October':[]}, {'November':[]}, {'December':[]}] const groupByDate = (data) => { return data.reduce((acc, currentValue) => { const month = moment(currentValue["date"]).format('MMMM'); const monthInAcc = acc.find((item)=>Object.keys(item).includes(month)); monthInAcc[month].push(currentValue) return acc; }, monthsAcc); }; console.log(groupByDate(seb)) // 注:此处seb为笔误,应为data
需求
- 返回结果仅包含值为非空数组的月份项
- 移除初始的
monthsAcc累加数组 - 接受其他重构建议
优化方案
方案1:返回对象格式(性能更优)
用普通对象作为累加器,自动生成有数据的月份,最后过滤空数组:
const moment = require('moment') const groupByDate = (data) => { // 空对象作为初始累加器,避免冗余月份初始化 const grouped = data.reduce((acc, item) => { const month = moment(item.date).format('MMMM'); // 不存在则初始化空数组 if (!acc[month]) { acc[month] = []; } acc[month].push(item); return acc; }, {}); // 过滤掉空数组的键,仅保留有数据的月份 return Object.fromEntries( Object.entries(grouped).filter(([_, items]) => items.length > 0) ); }; console.log(groupByDate(data));
输出结果:
{ November: [ { date: '2022-11-30T07:33:07.992955008Z', reponame: 'test-repo', category: 'veggy' }, { date: '2022-11-30T07:33:07.992956372Z', reponame: 'veggy-repo', category: 'fruit' }, { date: '2022-11-30T07:33:07.992956372Z', reponame: 'veggy-repo', category: 'veggy' }, { date: '2022-11-30T07:33:07.992956372Z', reponame: 'vegy-repo', category: 'vegy' } ] }
方案2:返回数组格式(贴近原结构)
如果需要保持原函数的数组结构(每个元素为单键对象),可在分组后转换:
const moment = require('moment') const groupByDate = (data) => { const grouped = data.reduce((acc, item) => { const month = moment(item.date).format('MMMM'); if (!acc[month]) { acc[month] = []; } acc[month].push(item); return acc; }, {}); // 转换为数组格式,仅保留非空分组 return Object.entries(grouped) .filter(([_, items]) => items.length > 0) .map(([month, items]) => ({ [month]: items })); }; console.log(groupByDate(data));
输出结果:
[ { November: [ { date: '2022-11-30T07:33:07.992955008Z', reponame: 'test-repo', category: 'veggy' }, { date: '2022-11-30T07:33:07.992956372Z', reponame: 'veggy-repo', category: 'fruit' }, { date: '2022-11-30T07:33:07.992956372Z', reponame: 'veggy-repo', category: 'veggy' }, { date: '2022-11-30T07:33:07.992956372Z', reponame: 'vegy-repo', category: 'vegy' } ] } ]
重构亮点
- 移除冗余的
monthsAcc数组,避免初始化未使用的月份 - 用对象替代数组作为累加器,月份查找复杂度从O(n)降至O(1),性能提升
- 自动过滤空数组,仅保留有数据的分组
- 修复原代码中
console.log的笔误 - 简化逻辑,代码可读性更强
内容的提问来源于stack exchange,提问作者AlexUA
相关产品推荐
相关产品推荐

