”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 JavaScript 中按多个属性和聚合值对对象进行分组?

如何在 JavaScript 中按多个属性和聚合值对对象进行分组?

发布于2024-12-25
浏览:622

How to Group Objects by Multiple Properties and Aggregate Values in JavaScript?

按多个属性对对象进行分组并聚合值

在按多个属性对数组中的对象进行分组的任务中,一个常见的要求是不仅可以按这些属性进行分组,还可以对某些对象属性的值进行求和。然而,简单地将所有重复项嵌套在二维数组中的解决方案是不够的。

问题陈述

考虑一个必须按形状分组的对象数组,并且颜色。仅当该数组中的对象的形状和颜色相同时,才会将其视为重复对象。对于重复的对象,我们需要总结它们的使用值和实例值,并删除重复项,从而得到具有独特形状和颜色的简洁对象列表。

解决方案

为了有效解决这个问题,我们可以结合使用 Array#reduce 方法和一个跟踪遇到的形状和颜色组合的辅助对象:

const arr = [
  { shape: 'square', color: 'red', used: 1, instances: 1 },
  { shape: 'square', color: 'red', used: 2, instances: 1 },
  { shape: 'circle', color: 'blue', used: 0, instances: 0 },
  { shape: 'square', color: 'blue', used: 4, instances: 4 },
  { shape: 'circle', color: 'red', used: 1, instances: 1 },
  { shape: 'circle', color: 'red', used: 1, instances: 0 },
  { shape: 'square', color: 'blue', used: 4, instances: 5 },
  { shape: 'square', color: 'red', used: 2, instances: 1 },
];

const helper = {};
const result = arr.reduce((r, o) => {
  const key = `${o.shape}-${o.color}`;

  if (!helper[key]) {
    // If it's a unique combination, add to the helper and result array
    helper[key] = Object.assign({}, o);
    r.push(helper[key]);
  } else {
    // If it's a duplicate, update the values in the helper
    helper[key].used  = o.used;
    helper[key].instances  = o.instances;
  }

  return r;
}, []);

console.log(result);

输出:

[
  { shape: "square", color: "red", used: 5, instances: 3 },
  { shape: "circle", color: "red", used: 2, instances: 1 },
  { shape: "square", color: "blue", used: 11, instances: 9 },
  { shape: "circle", color: "blue", used: 0, instances: 0 }
]

此解决方案按形状和颜色对对象进行有效分组,聚合重复对象的使用值和实例值,并删除任何剩余的重复项,从而产生所需的输出。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3