What’s the most efficient way to group by objects in an array in JavaScript and sum specific values?

Hello @keerti_gautam. I will tell you about one more solution in the discussion on grouping and summing array objects, especially since you mentioned your familiarity with Underscore.js.

Since you’re already familiar with Underscore.js, you can still use its **groupBy method** combined with map to handle both grouping and summing. This approach allows you to group by Phase, and then easily iterate over each group to sum the Value.

Here’s an example for grouping by Phase:

const data = [
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: 5 },
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: 10 },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: 15 },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: 20 },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: 25 },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: 30 },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: 35 },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: 40 }
];

const grouped = _.groupBy(data, 'Phase');
const summed = _.map(grouped, (group, Phase) => {
  const totalValue = _.reduce(group, (sum, obj) => sum + Number(obj.Value), 0);
  return { Phase, Value: totalValue };
});

console.log(summed);

Explanation:

  • groupBy is used to group the data by Phase.
  • map is then used to iterate over each group and sum the Value field using reduce.
  • The result is an array of objects with summed values by phase.

Hope this familiar approach helps you efficiently aggregate your data! And kudos to @emma-crepeau and @tim-khorev for their amazing solutions!!

Thanks!