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:
reducemethod: 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 ofnumentries 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.mapmethod: Transforms each pair back into an object withmonthandnumproperties, 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
相关产品推荐
相关产品推荐

