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

React中实现数组按月份和年份双重分组并聚合金额值的问题求助

解决React中按年月组合分组数组的问题

没问题,这事儿其实超简单,只需要调整一下你分组时的key生成逻辑,就能同时区分月份和年份啦!

核心思路

你之前的分组只用到了month作为唯一key,所以同月份不同年份的数据会被合并到一起。现在只需要把月份+年份组合成一个唯一的key(比如11/2020),就能让它们分到不同的组里。

修改后的完整代码

const paid = [
  {amount:155, month:11, year:2020, date:"11-11-2020"},
  {amount:120, month:11, year:2021, date:"05-11-2021"},
  {amount:135, month:12, year:2020, date:"11-12-2020"},
];

function groupBy(list, keyGetter) {
  const map = new Map();
  list.forEach((item) => {
    const key = keyGetter(item);
    const collection = map.get(key);
    if (!collection) {
      map.set(key, [parseInt(item.amount)]);
    } else {
      collection.push(parseInt(item.amount));
    }
  });
  return map;
}

// 关键修改:生成「月份/年份」的组合key
const groupMap = groupBy(paid, (item) => `${item.month}/${item.year}`);

// 将Map转换为你期望的数组结构
const grouped = Array.from(groupMap.entries()).map(([name, values]) => ({
  name,
  values
}));

console.log(grouped);

运行结果

这段代码会输出你想要的结构:

[
  {name: "11/2020", values: [155]},
  {name: "11/2021", values: [120]},
  {name: "12/2020", values: [135]}
]

可选优化(如果需要更友好的名称)

要是你希望name显示成更易读的格式(比如Nov 2020),可以调整keyGetter的逻辑:

const groupMap = groupBy(paid, (item) => 
  new Date(item.year, item.month - 1).toLocaleString('en-US', {
    month: 'short',
    year: 'numeric'
  })
);

这样生成的分组名称会是Nov 2020、Nov 2021这种样式,根据你的需求选择就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 10:42:41