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

如何使用JavaScript计算JSON数据值的平均值并完成指定次数迭代?分组计算作业difficulty与fun平均值的实现方案

用JavaScript快速实现作业难度与趣味度的分组平均值计算

嘿,我来帮你搞定这个问题!其实用JavaScript的reduce方法就能很优雅地完成分组和平均值计算,咱们一步步拆解,保证你能直接落地:

第一步:准备你的数据集

先模拟一份符合你描述的样本数据(你可以直接替换成自己的10条真实数据):

const studentData = [
  { name: "Evelyn", assignment: "SCRUM", difficulty: 3, fun: 4 },
  { name: "Liam", assignment: "SCRUM", difficulty: 4, fun: 5 },
  { name: "Olivia", assignment: "React Basics", difficulty: 2, fun: 3 },
  { name: "Noah", assignment: "React Basics", difficulty: 3, fun: 4 },
  { name: "Emma", assignment: "Node.js API", difficulty: 5, fun: 2 },
  { name: "Oliver", assignment: "Node.js API", difficulty: 4, fun: 3 },
  // 剩下4条数据你可以继续补充,不管有多少类作业,逻辑都通用
];

第二步:用reduce分组并统计总和与数量

reduce是处理这类聚合问题的神器,我们可以用它把相同作业的数据归到一组,同时统计每组的难度总和、趣味度总和,以及数据条数:

// 先分组统计核心数据
const groupedStats = studentData.reduce((accumulator, currentItem) => {
  // 如果当前作业还没被记录,初始化它的统计项
  if (!accumulator[currentItem.assignment]) {
    accumulator[currentItem.assignment] = {
      assignment: currentItem.assignment,
      totalDifficulty: 0,
      totalFun: 0,
      count: 0
    };
  }
  // 累加对应的数据
  accumulator[currentItem.assignment].totalDifficulty += currentItem.difficulty;
  accumulator[currentItem.assignment].totalFun += currentItem.fun;
  accumulator[currentItem.assignment].count += 1;
  
  return accumulator;
}, {}); // 初始值是空对象,用来存储分组结果

第三步:转换为带平均值的最终数组

现在我们已经有了每组的总和和数量,接下来只需要遍历这些分组数据,计算平均值并整理成你需要的JSON数组格式:

// 转换为包含平均值的最终数组
const finalResult = Object.values(groupedStats).map(group => ({
  assignment: group.assignment,
  avgDifficulty: (group.totalDifficulty / group.count).toFixed(2), // 保留两位小数,按需调整
  avgFun: (group.totalFun / group.count).toFixed(2)
}));

看看最终结果

打印finalResult就能得到你想要的结构化数据了,示例输出大概是这样:

console.log(finalResult);
// 输出:
// [
//   { assignment: 'SCRUM', avgDifficulty: '3.50', avgFun: '4.50' },
//   { assignment: 'React Basics', avgDifficulty: '2.50', avgFun: '3.50' },
//   { assignment: 'Node.js API', avgDifficulty: '4.50', avgFun: '2.50' }
// ]

额外小提示

  • 如果不需要固定小数位数,直接去掉.toFixed(2)即可,会得到原始的浮点数结果;
  • 如果你的数据里可能存在difficulty或fun为undefined的情况,可以在累加时加个兜底,比如currentItem.difficulty || 0,避免出现NaN;
  • 这个逻辑不管你有多少类作业(哪怕是56类)都能完美适配,时间复杂度是O(n),效率很高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:19:07