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

如何使用ES6统计JavaScript对象数组中指定属性的出现次数

ES6实现数组按指定属性分组统计次数

可以用ES6的Array.prototype.reduce实现,效率和手动for循环一致(时间复杂度均为O(n)),写法更简洁,还可以封装成通用函数适配任意属性的统计需求:

完整实现代码

// 示例源数组
const data = [
  {
    "firstName": "Bob",
    "lastName": "Smith",
    "city": "Preston",
    "st": "Florida",
    "age": 15
  },
  {
    "firstName": "Tom",
    "lastName": "Jones",
    "city": "Springfield",
    "st": "Illinois",
    "age": 34
  },
  {
    "firstName": "Mary",
    "lastName": "Hart",
    "city": "Miami",
    "st": "Florida",
    "age": 22
  },
  {
    "firstName": "Jenny",
    "lastName": "Dixon",
    "city": "Palm City",
    "st": "Florida",
    "age": 26
  }
];

/**
 * 按指定属性统计数组中该属性不同值的出现次数
 * @param {Array} arr 源对象数组
 * @param {String} prop 要统计的属性名
 * @returns {Array} 统计结果数组
 */
const countByProp = (arr, prop) => {
  // 第一步:遍历数组生成统计映射表
  const countMap = arr.reduce((accumulator, current) => {
    const key = current[prop];
    accumulator[key] = (accumulator[key] || 0) + 1;
    return accumulator;
  }, {});
  // 第二步:将映射表转换为要求的输出格式
  return Object.entries(countMap).map(([propValue, count]) => ({
    [prop]: propValue,
    count
  }));
}

// 调用示例:统计州(st)的出现次数
const result = countByProp(data, 'st');
console.log(result);

输出结果

运行上述代码后得到的result就是你要求的格式:

[
  {
    "st": "Florida",
    "count": 3
  },
  {
    "st": "Illinois",
    "count": 1
  }
]

逻辑说明

  • reduce方法遍历数组时,会把每个对象指定属性的值作为键,累计出现次数存入初始的空对象中,仅需一次遍历即可完成统计,没有额外性能损耗。
  • Object.entries+map的组合用来把统计用的键值对对象,转换为你需要的数组嵌套对象格式。
  • 该函数通用,传入其他属性名即可统计对应字段,比如传入age就能统计不同年龄的出现次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:54:01