Grouping Arrays of Objects in JavaScript

Grouping arrays of objects is a common task in JavaScript, and it can be achieved using various methods. In this tutorial, we will explore how to group an array of objects by one or more properties and calculate the sum of specific values.

Introduction to GroupBy

The groupBy function takes an array of objects and a key function as input. The key function returns a value that is used to group the objects. For example, if we have an array of objects with phase, step, and task properties, we can use the phase property as the key to group the objects.

Using Reduce to GroupBy

One way to implement the groupBy function is by using the reduce method. The reduce method applies a function to each element in the array and returns a single value. We can use this method to create an object where the keys are the unique values of the key property, and the values are arrays of objects that have that key.

const groupBy = (array, key) => {
  return array.reduce((result, item) => {
    (result[item[key]] ??= []).push(item);
    return result;
  }, {});
};

Using Map to GroupBy

Another way to implement the groupBy function is by using the Map object. The Map object allows us to store key-value pairs where the keys are unique.

const groupByToMap = (array, key) => {
  return array.reduce((map, item) => {
    const k = item[key];
    map.get(k)?.push(item) ?? map.set(k, [item]);
    return map;
  }, new Map());
};

Calculating the Sum of Specific Values

To calculate the sum of specific values, we can use the reduce method again. This time, we will apply the reduce method to each group of objects.

const groupByAndSum = (array, key, valueKey) => {
  return array.reduce((result, item) => {
    const k = item[key];
    if (!result[k]) {
      result[k] = { [key]: k, [valueKey]: 0 };
    }
    result[k][valueKey] += parseInt(item[valueKey]);
    return result;
  }, {});
};

Example Use Cases

Here are some example use cases:

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 groupedByPhase = groupBy(data, 'phase');
console.log(groupedByPhase);

const summedByPhase = groupByAndSum(data, 'phase', 'value');
console.log(summedByPhase);

Conclusion

In this tutorial, we have learned how to group an array of objects by one or more properties and calculate the sum of specific values. We have also seen example use cases that demonstrate how to apply these concepts in practice.

Leave a Reply

Your email address will not be published. Required fields are marked *