-2

My array is something like this:

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

Basically in the result, I want to calculate the each object's weight percentage in the respective phase. For example, first object weight percentage is 20/(20 + 40) * 100 = 0.333 as this belongs to phase one.

And result should be like this.

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"}
]
4castle
  • 32,613
  • 11
  • 69
  • 106
Ravi
  • 1
  • 1

1 Answers1

0

First create a dictionary of phases and weights, so that you can find the sum of all weights for a specific phase. Then loop over the phase objects to set the percentage.

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);
4castle
  • 32,613
  • 11
  • 69
  • 106