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

JavaScript对象月份对应值计算:重复月份num求和,唯一月份保留原值

Solution for Summing Monthly Values

Here's a straightforward, efficient way to get your desired result using JavaScript:

const originalData = [ 
  {num: 5000, month: "September"}, 
  {num: 6000, month: "September"}, 
  {num: 4500, month: "August"}, 
  {num: 3500, month: "August"}, 
  {num: 5000, month: "jan"}, 
  {num: 6000, month: "feb" } 
];

// Calculate total sums per month
const monthlySums = originalData.reduce((acc, { num, month }) => {
  acc[month] = (acc[month] || 0) + num;
  return acc;
}, {});

// Convert the sum object back to your target array format
const result = Object.entries(monthlySums).map(([month, num]) => ({ month, num }));

console.log(result);

Output:

[
  { num: 11000, month: 'September' },
  { num: 8000, month: 'August' },
  { num: 5000, month: 'jan' },
  { num: 6000, month: 'feb' }
]

Breakdown of how it works:

  • reduce method: We loop through the original array once to build an object where each key is a month name, and the value is the total sum of num entries for that month. The (acc[month] || 0) ensures we start counting from zero if the month hasn't been encountered yet.
  • Object.entries: Converts our sum object into an array of [month, total] pairs.
  • map method: Transforms each pair back into an object with month and num properties, exactly matching your desired output structure.

This approach runs in O(n) time (linear complexity) since we only iterate the original array once plus the resulting sum object once—making it both fast and easy to maintain.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:38:22