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

JavaScript如何按a、b、c属性分组对象数组生成聚合结果

JavaScript按指定属性合并数组的高效实现

实现思路

  • 用哈希表(Map/普通对象)存储分组,以a、b、c三个属性的序列化结果作为唯一键,确保相同属性组合的项会被分到同一组
  • 仅需遍历原数组一次完成分组,最终把哈希表的值转为数组即可得到目标结果,时间复杂度为O(n),远优于暴力循环的O(n²)

代码实现

现代ES6+实现(推荐)

function groupByABC(arr) {
  const groupMap = new Map();
  arr.forEach(item => {
    // 序列化三个属性生成唯一键,自动规避分隔符冲突问题
    const key = JSON.stringify({a: item.a, b: item.b, c: item.c});
    if (!groupMap.has(key)) {
      // 初始化新分组
      groupMap.set(key, {
        a: item.a,
        b: item.b,
        c: item.c,
        pets: []
      });
    }
    // 追加当前项的pet和age到分组
    groupMap.get(key).pets.push({
      pet: item.pet,
      age: item.age
    });
  });
  // 转换为数组返回
  return Array.from(groupMap.values());
}

// 测试用例
const myArray = [
  {a: 'animal', b: 'white', c: true, pet: 'dog1', age: 1},
  {a: 'animal', b: 'white', c: true, pet: 'dog2', age: 2},
  {a: 'animal2', b: 'white', c: true, pet: 'cat1', age: 5},
  {a: 'animal2', b: 'black', c: false, pet: 'cat2', age: 1}
];
const outputArray = groupByABC(myArray);
console.log(outputArray);

兼容旧环境实现

如果需要支持不支持Map的旧JS环境,可以用普通对象替代:

function groupByABC(arr) {
  const groupObj = {};
  arr.forEach(item => {
    const key = JSON.stringify({a: item.a, b: item.b, c: item.c});
    if (!groupObj[key]) {
      groupObj[key] = {
        a: item.a,
        b: item.b,
        c: item.c,
        pets: []
      };
    }
    groupObj[key].pets.push({pet: item.pet, age: item.age});
  });
  return Object.values(groupObj);
}

如果确认三个属性的值都不会包含特殊分隔符,也可以手动拼接键${item.a}|${item.b}|${item.c},性能比JSON.stringify稍高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:24:03