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

JavaScript实现两个数组相同日期的数据合并方案

合并两个数组中同日期的图片数据

可以通过以下步骤实现需求:

  • 将两个数组合并为一个数组
  • 以date为键对数据分组,合并对应日期下的images数组
  • 将分组结果转换为目标格式的数组

实现代码

const list1 = [{
  date: "2022-10-01",
  images: [{image: "01"}, {image: "02"}, {image: "03"}]
}]
const list2 = [{
    date: "2022-10-01",
    images: [{ image: "04"}]
  },
  {date: "2022-10-02",
   images: [{image: "05"}, {image: "06"}, { image: "07"}]
  }
]

// 合并数组并处理日期分组与图片合并
const mergedResult = [...list1, ...list2].reduce((acc, current) => {
  const existingItem = acc.find(item => item.date === current.date);
  if (existingItem) {
    existingItem.images = [...existingItem.images, ...current.images];
  } else {
    acc.push({...current});
  }
  return acc;
}, []);

console.log(mergedResult);

代码说明

  • [...list1, ...list2]:将两个输入数组合并为新数组,避免修改原数据
  • reduce方法:遍历合并后的数组,用累加器acc存储最终结果
  • 对每个元素,通过find检查累加器中是否存在相同日期的项:
    • 存在则将当前元素的images数组合并到已有项的images中
    • 不存在则将当前元素的副本添加到累加器中
  • 最终累加器即为按日期合并后的目标数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:35:19