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

JS对象数组如何计算各属性的最小值、最大值与平均值

JavaScript对象数组属性值统计实现

需求说明

现有一个存储多组数值的JavaScript对象数组,所有数值以字符串格式存储,需要统计数组内每个公共属性对应的最小值、最大值与平均值,最终按指定结构输出统计结果。

示例输入

const array = [{
    "a": "-0.06",
    "b": "0.25",
    "c": "-0.96",
    "d": "-0.14"
  },
  {
    "a": "-0.37",
    "b": "0.01",
    "c": "-0.77",
    "d": "-0.09"
  },
  {
    "a": "0.01",
    "b": "0.88",
    "c": "-0.53",
    "d": "-0.28"
  },
  {
    "a": "0.53",
    "b": "-0.62",
    "c": "0.02",
    "d": "0.74"
  },
  {
    "a": "0.79",
    "b": "-0.39",
    "c": "0.70",
    "d": "0.18"
  },
  {
    "a": "0.74",
    "b": "-0.14",
    "c": "0.22",
    "d": "-0.58"
  }
]

期望输出结构

const out = [{
  property: 'a',
  minValue: -0.37,
  maxValue: .79,
  avg: 0.2733333333333334
}, {
  property: 'b',
  minValue: -.62,
  maxValue: .88,
  avg: -0.0016666666666666496
}, {
  property: 'c',
  minValue: -.96,
  maxValue: .70,
  avg: -0.21999999999999997
}, {
  property: 'd',
  minValue: -.58,
  maxValue: .74,
  avg: -0.028333333333333332
}]

注:原示例中属性c的maxValue标注为.07属于笔误,实际统计最大值为0.70

实现代码

核心逻辑是先提取所有待统计的属性名,再逐个属性收集所有值、转成数字类型后计算最值和平均值:

function calcPropertyStats(arr) {
  // 空数组兜底
  if (!arr.length) return [];
  // 获取所有公共属性
  const properties = Object.keys(arr[0]);
  
  return properties.map(prop => {
    // 提取当前属性所有值并转为数字类型
    const numValues = arr.map(item => Number(item[prop]));
    // 计算统计指标
    const minValue = Math.min(...numValues);
    const maxValue = Math.max(...numValues);
    const avg = numValues.reduce((total, val) => total + val, 0) / numValues.length;
    
    return { property: prop, minValue, maxValue, avg };
  })
}

// 调用即可得到期望结果
const out = calcPropertyStats(array);

注意事项

  • 原始数据中的数值为字符串格式,必须先转成Number类型再做计算,否则字符串比较大小、求和都会出现逻辑错误
  • 代码做了空数组兜底,传入空数组时不会报错,直接返回空结果
  • 如果数组对象存在非公共属性,当前逻辑只会统计第一个对象包含的属性,可按需调整属性提取逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 13:09:26