如何合并多个filter为单个过滤函数取指定月份值并降低时间复杂度
优化实现
你现有写法每查询一个月的数据就会全量遍历一次原始数组,查询k个月的时间复杂度是O(kn),可以通过单次遍历完成所有月份数据归类,时间复杂度直接降到O(n),和你原有代码输出完全一致的实现如下:
// 原始数据不变 const getrewarddata = [{ month: 6, year: 2021, reward: 6, }, { month: 1, year: 2021, reward: 6, }, { month: 3, year: 2021, reward: 6, }, ]; // 初始化下标0-12的空数组,下标对应月份,0位空置不用 const monthCollection = Array.from({length: 13}, () => []); // 单次遍历完成所有数据归类 for (const item of getrewarddata) { monthCollection[item.month].push(item); } // 直接按月份取对应数据即可,d1对应1月、d2对应2月以此类推 const [, d1, d2, d3] = monthCollection; console.log(d2); // 输出[] 符合原有逻辑 console.log(d3); // 输出[{month: 3, year: 2021, reward: 6}] 符合原有逻辑
如果只需要特定几个月份的数据,不需要覆盖全年12个月,也可以用以下更节省空间的写法:
const getrewarddata = [ { month: 6, year: 2021, reward: 6 }, { month: 1, year: 2021, reward: 6 }, { month: 3, year: 2021, reward: 6 }, ]; // 只初始化你需要查询的月份 const targetMonths = { 1: [], 2: [], 3: [] } for (const item of getrewarddata) { // 只处理目标月份的数据 if (targetMonths[item.month]) { targetMonths[item.month].push(item); } } const d1 = targetMonths[1], d2 = targetMonths[2], d3 = targetMonths[3];
该方案的优势:
- 仅需要遍历一次原始数组,数据量越大、需要查询的月份越多,效率提升越明显
- 后续如果需要新增其他月份的数据,直接从归类结果里取即可,不需要新增过滤逻辑重复遍历数组
内容的提问来源于stack exchange,提问作者tirth1620
相关产品推荐
相关产品推荐

