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

JavaScript中按对象属性分组并统计数量的实现方案

JavaScript: 按指定属性列表分组并统计每组数量

问题描述

我有一个嵌套结构的对象数组temp,想要根据传入的属性列表(比如["gender","status"]),分别按每个属性分组并统计每组的数量。

示例数组:

const temp = [ 
  { properties: { "id":1234, "gender": 'male', "status": "Active" } }, 
  { properties: { "id":1456, "gender": 'male', "status": "Not Active" } }, 
  { properties: { "id":1377, "gender": 'female', "status": "Active" } }, 
  { properties: { "id":8799, "gender": 'female', "status": "Active" } } 
];

我尝试实现了groupFunc函数但有问题,期望得到的分组统计结果如下:

grouped = [ 
  [ { "key": "gender", "value": "male", "count": 2 }, { "key": "gender", "value": "female", "count": 2 } ], 
  [ { "key": "status", "value": "Active", "count": 3 }, { "key": "status", "value": "Not Active", "count": 1 } ] 
]

解决方案

这里给你两种实现方式,都能精准满足你的需求:

方式一:逻辑直观的forEach写法

这种写法步骤清晰,新手也能快速理解:

function groupFunc(attributes) {
  // 遍历每个需要统计的属性,生成对应分组结果
  return attributes.map(attr => {
    const countMap = {};
    
    // 遍历原数组,统计当前属性每个值的出现次数
    temp.forEach(item => {
      const value = item.properties[attr];
      countMap[value] = (countMap[value] || 0) + 1;
    });
    
    // 将计数对象转换为期望的数组格式
    return Object.entries(countMap).map(([value, count]) => ({
      key: attr,
      value,
      count
    }));
  });
}

// 测试调用
const grouped = groupFunc(["gender", "status"]);
console.log(grouped);

方式二:简洁的reduce函数式写法

如果喜欢更紧凑的代码风格,可以用reduce简化统计逻辑:

function groupFunc(attributes) {
  return attributes.map(attr => {
    // 用reduce一次性生成计数映射
    const countMap = temp.reduce((acc, item) => {
      const value = item.properties[attr];
      acc[value] = (acc[value] || 0) + 1;
      return acc;
    }, {});
    
    // 转换为目标格式
    return Object.entries(countMap).map(([value, count]) => ({
      key: attr,
      value,
      count
    }));
  });
}

核心逻辑说明

  1. 逐个处理属性:通过map遍历传入的属性列表,为每个属性单独生成统计结果,保证结果数组的结构和属性列表顺序一致。
  2. 高效计数:用临时对象countMap存储每个属性值的出现次数,只需要遍历原数组一次就能完成单个属性的统计。
  3. 格式转换:Object.entries把对象的键值对转换成数组,再通过map映射成你需要的{key, value, count}结构,完美匹配期望输出。

这两种方式都能输出你想要的结果,选自己看着顺眼的用就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 11:03:14