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

重构:如何用外部函数实现JavaScript中.reduce的分组求和逻辑?

标题建议:如何将JavaScript中reduce的分组求和逻辑提取为通用函数以遵循DRY原则?

你的代码问题分析

你写的sumAll函数存在几个核心问题:

  • 调用时直接传phoNumbId、mount会被当作未定义变量,实际需要传字符串形式的键名
  • 函数内部依赖外部的res和value,但这两个是reduce回调的专属参数,未传入函数
  • 对象字面量里直接用firstValue当键名,会被解析为字符串"firstValue",而非动态的参数值,需用方括号[firstValue]实现动态键名
  • 拼写错误:primerValor应为firstValue

正确的通用分组求和函数实现

下面提供两种符合DRY原则的实现方案,适配不同场景需求:

方案1:整合结果数组的通用函数

直接在函数内处理结果数组的推送,和原逻辑保持一致:

function groupAndSum(res, value, groupKey, sumKey, resultArray) {
  const groupValue = value[groupKey];
  if (!res[groupValue]) {
    // 用方括号实现动态键名,确保分组键和求和键与传入参数一致
    res[groupValue] = { [groupKey]: groupValue, [sumKey]: 0 };
    resultArray.push(res[groupValue]);
  }
  res[groupValue][sumKey] += value[sumKey];
  return res;
}

调用方式:

var result2 = [];
nexus.reduce((res, value) => {
  return groupAndSum(res, value, 'phoNumbId', 'mount', result2);
}, {});

// 输出结果:
// [
//   { phoNumbId: 1, mount: 1700 },
//   { phoNumbId: 2, mount: 5500 },
//   { phoNumbId: 3, mount: 42020 }
// ]

方案2:纯函数版本(无副作用)

如果希望函数更符合函数式编程思想,不依赖外部数组,可只返回分组后的对象,最后再转成数组:

function groupAndSumPure(res, value, groupKey, sumKey) {
  const groupValue = value[groupKey];
  if (!res[groupValue]) {
    res[groupValue] = { [groupKey]: groupValue, [sumKey]: 0 };
  }
  res[groupValue][sumKey] += value[sumKey];
  return res;
}

调用方式:

const groupedObj = nexus.reduce((res, value) => {
  return groupAndSumPure(res, value, 'phoNumbId', 'mount');
}, {});
// 将分组对象的值转为数组
const result2 = Object.values(groupedObj);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:30:41