如何将值推入子数组,避免新增日期条目?
解决方法:按日期归类数据到dateList
嘿,我来帮你搞定这个分组的问题!你现在的代码已经做了日期存在性判断,但缺了找到已有日期条目时添加数据的关键步骤,而且我们可以把代码优化得更简洁高效。
核心思路很简单:遍历resultList的每一项时,先检查dateList里是否已经有对应日期的条目。如果有,就把当前项的amount包装成对象推到该条目的amounts数组里;如果没有,就新建一个日期条目加入dateList。
方法一:直接遍历查找(适合数据量不大的场景)
用find方法替代嵌套的forEach,代码更简洁,可读性更强:
this.resultList.forEach((result) => { // 查找dateList中是否已有当前日期的条目 const existingItem = this.dateList.find(item => item.date === result.date); if (existingItem) { // 找到已有条目,将当前amount推入其amounts数组 existingItem.amounts.push({ amount: result.amount }); } else { // 无对应条目,创建新条目并加入dateList this.dateList.push({ date: result.date, amounts: [{ amount: result.amount }] }); } });
方法二:用Map做中间映射(适合大数据量场景)
如果你的resultList数据量很大,用find每次遍历dateList会有点低效。这时可以用Map来做中间存储,查找效率是O(1),整体时间复杂度从O(n²)降到O(n):
// 初始化Map,key为日期字符串,value为对应的amounts数组 const dateMap = new Map<string, { amount: number }[]>(); this.resultList.forEach((result) => { if (dateMap.has(result.date)) { // 已有该日期,追加amount对象 dateMap.get(result.date)!.push({ amount: result.amount }); } else { // 无该日期,初始化数组并存入Map dateMap.set(result.date, [{ amount: result.amount }]); } }); // 将Map转换为dateList需要的格式 this.dateList = Array.from(dateMap.entries()).map(([date, amounts]) => ({ date, amounts }));
这两种方法都能完美实现你要的按日期归类的需求,根据你的数据规模选合适的就行~
内容的提问来源于stack exchange,提问作者DFSFOT
相关产品推荐
相关产品推荐

