【问题标题】:javascript - Group by an element from array of objectsjavascript - 按对象数组中的元素分组
【发布时间】:2017-08-30 03:35:57
【问题描述】:

我的数组是这样的:

Array= [
  {phase: "one", weight: "10"},
  {phase: "one", weight: "20"},
  {phase: "two", weight: "30"},
  {phase: "two", weight: "40"}
]

基本上在结果​​中,我想计算每个对象在各个阶段的重量百分比。例如,第一个对象权重百分比是20/(20 + 40) * 100 = 0.333,因为它属于第一阶段。

结果应该是这样的。

Array= [
  {phase: "one", weight: "20", percentage:"0.333"},
  {phase: "one", weight: "40", percentage:"0.666"},
  {phase: "two", weight: "30", percentage:"0.3"},
  {phase: "two", weight: "70", percentage:"0.7"}
]

【问题讨论】:

标签: javascript typescript arraylist


【解决方案1】:

首先创建一个阶段和权重的字典,以便您可以找到特定阶段的所有权重的总和。然后遍历阶段对象来设置百分比。

const phases = [
  { phase: "one", weight: 10 },
  { phase: "one", weight: 20 },
  { phase: "two", weight: 30 },
  { phase: "two", weight: 40 }
];

const phaseWeights = phases.reduce(
  (dict, {phase, weight}) => {
    dict[phase] = (dict[phase] || 0) + weight;
    return dict;
  },
  Object.create(null)
);

phases.forEach((phaseObj) => {
  const {phase, weight} = phaseObj;
  phaseObj.percentage = weight / phaseWeights[phase] * 100;
});

console.log(phases);

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 2017-03-18
    • 2020-09-19
    • 2014-07-05
    • 2023-04-05
    • 2021-02-23
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多