Home >Web Front-end >JS Tutorial >How Can Underscore.js Efficiently Group and Sum Data in an Array of Objects?
Efficient GroupBy for Array of Objects using Underscore.js
Grouping data in an array of objects is essential for aggregating and analyzing information. This is particularly important when working with structured data. Among various methods, Underscore.js offers a powerful solution for grouping objects based on specific criteria.
In this case, you want to group the objects by various combinations of fields, such as Phase and Step, while also summing the corresponding values. Underscore.js provides a groupBy function that can handle this task efficiently.
Here's an example of how to use Underscore.js to group the array of objects 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 groupedByPhase = _.groupBy(data, 'Phase');
This operation results in an object where the keys are the distinct values of Phase, and the values are arrays of objects that belong to each phase. To calculate the total value for each phase, you can use the reduce function as follows:
const phaseTotals = _.map(groupedByPhase, function(phaseData) { return { Phase: phaseData[0].Phase, Value: _.reduce(phaseData, function(memo, object) { return memo + Number(object.Value); }, 0) }; });
Similarly, you can group the objects by any combination of fields using the same principle. By leveraging Underscore.js's groupBy function, you can efficiently group your data, providing valuable insights into your dataset.
The above is the detailed content of How Can Underscore.js Efficiently Group and Sum Data in an Array of Objects?. For more information, please follow other related articles on the PHP Chinese website!