数组日期重复值统计及缺失日期补0实现求助
解决方案
实现思路
- 统计原数组中每个日期的出现频次
- 确定日期区间的起始和结束,生成该区间内的所有连续日期
- 遍历连续日期数组,匹配频次统计结果,缺失日期补0
代码实现
// 原日期数组 let arr = ['02-11-2022', '02-11-2022', '03-11-2022', '04-11-2022', '04-11-2022', '04-11-2022', '05-11-2022', '07-11-2022']; // 步骤1:统计每个日期的出现次数 const countMap = new Map(); arr.forEach(date => { countMap.set(date, (countMap.get(date) || 0) + 1); }); // 步骤2:生成日期区间内的所有连续日期 // 转换日期字符串为Date对象,方便排序和生成连续日期 const dateObjects = [...countMap.keys()].map(dateStr => { const [day, month, year] = dateStr.split('-'); return new Date(year, month - 1, day); // 月份是0基索引,需减1 }); // 确定区间的最早和最晚日期 const minDate = new Date(Math.min(...dateObjects)); const maxDate = new Date(Math.max(...dateObjects)); // 生成格式统一的连续日期数组 const continuousDates = []; let currentDate = new Date(minDate); while (currentDate <= maxDate) { const day = String(currentDate.getDate()).padStart(2, '0'); const month = String(currentDate.getMonth() + 1).padStart(2, '0'); const year = currentDate.getFullYear(); continuousDates.push(`${day}-${month}-${year}`); currentDate.setDate(currentDate.getDate() + 1); } // 步骤3:生成最终结果数组 const newArr = continuousDates.map(date => countMap.get(date) || 0); console.log(newArr); // 输出:[2, 1, 3, 1, 0, 1]
代码说明
- 用
Map统计频次比普通对象更安全,避免日期字符串和对象属性名冲突 - 转换
Date对象是为了方便计算连续日期,注意原日期格式是DD-MM-YYYY,拆分时要对应好年、月、日的顺序 padStart(2, '0')保证日期和月份都是两位数字,和原数组格式统一- 最后遍历连续日期数组,直接映射频次,缺失的日期自动补0
内容的提问来源于stack exchange,提问作者gedamo
相关产品推荐
相关产品推荐

