You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:如何根据日期将对象分组到不同数组中?

根据日期属性分组对象数组的解决方案

要实现按对象的date属性分组,核心思路是先通过唯一标识键把相同日期的对象归类,再将归类后的结果转为二维数组,具体实现如下:

实现代码

const arr = [
    { obj: 1, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 2, date: {day: '9', month: 'Jan', year: '2022'} },
    { obj: 3, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 4, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 5, date: {day: '9', month: 'Jan', year: '2022'} },
    { obj: 6, date: {day: '14', month: 'Oct', year: '2023'} },
];

// 1. 用reduce构建分组映射
const groupedMap = arr.reduce((map, item) => {
    // 生成唯一的日期键:拼接day/month/year
    const dateKey = `${item.date.day}-${item.date.month}-${item.date.year}`;
    // 如果键不存在,初始化空数组;否则把当前item加入数组
    if (!map[dateKey]) {
        map[dateKey] = [];
    }
    map[dateKey].push(item);
    return map;
}, {});

// 2. 把映射的values转为二维数组,就是最终结果
const result = Object.values(groupedMap);

console.log(result);

代码说明

  • Array.reduce():遍历原始数组,逐步构建一个以日期键为key、对应分组数组为value的映射对象。
  • 日期键生成:通过拼接day/month/year生成唯一标识,确保相同日期的对象会被分到同一组。
  • Object.values():提取映射对象中的所有分组数组,组成最终的二维数组结构,和你期望的输出完全一致。

内容的提问来源于stack exchange,提问作者vinograd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:01:06