You need to enable JavaScript to run this app. 如何在JavaScript中计算对象数组分组后的属性平均值
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中计算对象数组分组后的属性平均值

实现方案

你可以使用reduce配合map实现分组求平均值,完整代码如下:

const array = [
  {
    createdAt: "2021-06-05",
    value: 0.2
  },
  {
    createdAt: "2021-06-05",
    value: 0.2
  },
  {
    createdAt: "2021-06-05",
    value: 1
  },
  {
    createdAt: "2021-06-06",
    value: 0.2
  },
  {
    createdAt: "2021-06-06",
    value: 0.3
  },
  {
    createdAt: "2021-06-06",
    value: 0.8
  },
  {
    createdAt: "2021-06-07",
    value: 0.7
  },
  {
    createdAt: "2021-06-07",
    value: 0.7
  },
  {
    createdAt: "2021-06-08",
    value: 0.7
  },
  {
    createdAt: "2021-06-08",
    value: 0.2
  }, 
  {
    createdAt: "2021-06-08",
    value: 0.9  
  }
]

// 分组统计每个日期的value总和、条目总数
const dateStats = array.reduce((result, current) => {
  const date = current.createdAt
  if (!result[date]) {
    result[date] = { sum: 0, count: 0 }
  }
  result[date].sum += current.value
  result[date].count += 1
  return result
}, {})

// 转换为目标格式,计算平均值并保留三位小数
const newArray = Object.entries(dateStats).map(([date, stats]) => ({
  createdAt: date,
  value: Number((stats.sum / stats.count).toFixed(3))
}))

运行后得到的newArray和你期望的输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 07:15:04