如何按当月1日至当前日分组含On Rent时间的JavaScript数组
需求说明
给定数组a,需要按每个对象中On Rent对应的日期(忽略具体时间)对数组元素分组,分组需覆盖当月1日至当前日的所有日期,无对应数据的日期保留空数组,最终输出格式需包含所有日期节点(无数据节点为空数组)。
给定数组:
const a = [ { "record_id": "2ff8212f-5ec9-4453-b1f3-91840a3fb152", "status_date_activity": { "On Rent": 1663841740869 } }, { "record_id": "c8c11f97-5eda-4f9b-a6a0-5a3f259c85b6", "status_date_activity": { "On Rent": 1663826452195 } }, { "record_id": "8c23aa44-4113-4feb-92b7-eb265f3e11e2", "status_date_activity": { "On Rent": 1663837445146, "Draft": 1663808712701, "Active": 1663808565409 } }, { "record_id": "fd88fbfc-a8d3-4a86-b245-0f8334b4f11f", "status_date_activity": { "On Rent": 1663841622113 } }, { "record_id": "e0ed3dcf-943c-48d1-b387-87e758e5ed9a", "status_date_activity": { "On Rent": 1663814717259, "Unprepped": 1663841617839 } }, { "record_id": "cef4d093-0ced-4d0d-b9f6-90c2e2687bbe", "status_date_activity": { "On Rent": 1663892940412 } } ]
现有基础分组代码(需补充日期范围逻辑):
const b = a.reduce((acc,curr)=>{ const dateN = new Date(curr.status_date_activity?.['On Rent']).toLocaleDateString("en-us", { day: "numeric", month: "short" }) return { ...acc, [dateN]:[...(acc[dateN] ?? []),curr] } },{})
完整实现代码
// 1. 获取当前日期与当月首日 const currentDate = new Date(); const firstDateOfTheMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); // 2. 生成当月1日至当前日的所有日期字符串(格式如"Sept 22") const generateDateRange = (start, end) => { const dates = []; let current = new Date(start); while (current <= end) { const dateStr = current.toLocaleDateString("en-us", { day: "numeric", month: "short" }); dates.push(dateStr); current.setDate(current.getDate() + 1); } return dates; }; const dateRange = generateDateRange(firstDateOfTheMonth, currentDate); // 3. 执行基础分组(优化:跳过无On Rent时间的对象) const groupedData = a.reduce((acc, curr) => { const onRentTimestamp = curr.status_date_activity?.['On Rent']; if (!onRentTimestamp) return acc; const dateN = new Date(onRentTimestamp).toLocaleDateString("en-us", { day: "numeric", month: "short" }); return { ...acc, [dateN]: [...(acc[dateN] ?? []), curr] }; }, {}); // 4. 构建最终结果:覆盖所有日期,无数据的日期设为空数组 const final_result = dateRange.map(dateStr => ({ [dateStr]: groupedData[dateStr] ?? [] })); console.log(final_result);
代码说明
- 生成日期范围:通过循环遍历从当月首日到当前日的所有日期,生成统一格式的日期字符串,确保分组覆盖完整区间。
- 分组逻辑优化:增加判断跳过无
On Rent时间的对象,避免无效计算。 - 构建结果数组:遍历生成的日期范围,从分组数据中匹配对应日期的结果,无数据则赋值为空数组,最终得到符合要求的结构。
内容的提问来源于stack exchange,提问作者cypher
相关产品推荐
相关产品推荐

