React考勤项目中提取JavaScript对象数组的唯一日期
解决React考勤项目中筛选唯一日期记录的问题
针对你遇到的筛选唯一日期(忽略时间部分)的需求,这里提供两种实用的解决方案:
方法一:利用ISO字符串截取(简洁高效)
由于你的考勤时间是标准ISO格式(YYYY-MM-DDTHH:mm:ss.sssZ),直接截取字符串前10位就能得到唯一的年月日标识,结合Set来跟踪已出现的日期即可快速过滤:
let dates = [ { id: 51, attendanceTime: "2022-12-26T06:07:02.000Z" }, { id: 52, attendanceTime: "2022-11-26T06:07:36.000Z" }, { id: 53, attendanceTime: "2022-10-12T06:28:43.000Z" }, { id: 54, attendanceTime: "2023-01-01T06:48:53.000Z" }, { id: 55, attendanceTime: "2022-12-26T06:56:23.000Z" }, ]; const seenDates = new Set(); const uniqueDateRecords = dates.filter(item => { // 截取前10位得到YYYY-MM-DD格式的日期键 const dateKey = item.attendanceTime.slice(0, 10); if (!seenDates.has(dateKey)) { seenDates.add(dateKey); return true; } return false; }); console.log(uniqueDateRecords);
这个方法会保留每个日期的第一条记录,完全符合你期望的输出结果,而且性能最优,因为只需要一次遍历和简单的字符串操作。
方法二:Date对象UTC处理(通用兼容)
如果你的日期字符串可能存在时区差异,或者格式不固定,推荐用UTC方法提取年月日,避免本地时区偏移导致的判断错误:
let dates = [ { id: 51, attendanceTime: "2022-12-26T06:07:02.000Z" }, { id: 52, attendanceTime: "2022-11-26T06:07:36.000Z" }, { id: 53, attendanceTime: "2022-10-12T06:28:43.000Z" }, { id: 54, attendanceTime: "2023-01-01T06:48:53.000Z" }, { id: 55, attendanceTime: "2022-12-26T06:56:23.000Z" }, ]; const uniqueDateRecords = dates.filter((item, index, self) => { const currentDate = new Date(item.attendanceTime); // 构造UTC的年月日字符串,保证格式统一 const dateKey = `${currentDate.getUTCFullYear()}-${String(currentDate.getUTCMonth() + 1).padStart(2, '0')}-${String(currentDate.getUTCDate()).padStart(2, '0')}`; // 只保留当前日期在数组中第一次出现的记录 return self.findIndex(record => { const recordDate = new Date(record.attendanceTime); const recordDateKey = `${recordDate.getUTCFullYear()}-${String(recordDate.getUTCMonth() + 1).padStart(2, '0')}-${String(recordDate.getUTCDate()).padStart(2, '0')}`; return recordDateKey === dateKey; }) === index; }); console.log(uniqueDateRecords);
这里用getUTCFullYear、getUTCMonth、getUTCDate来获取UTC时间的年月日,避免了不同时区下日期判断出错的问题,padStart(2, '0')确保月份和日期是两位数字(比如1月转为01),保证日期键的格式一致性。
内容的提问来源于stack exchange,提问作者Muhammad Salman Ashraf
相关产品推荐
相关产品推荐

