Home >Web Front-end >JS Tutorial >How Can I Efficiently Group an Array of Objects in JavaScript Using a Vanilla Approach?
Grouping objects based on common properties is a common task in data processing. This snippet provides an efficient solution to group objects in an array using a vanilla JavaScript approach.
While Underscore.js offers a groupBy function, its implementation may not be suitable if you require "merged" results rather than separate groups.
The following script defines a groupBy function that operates on an array of objects:
var groupBy = function(xs, key) { return xs.reduce(function(rv, x) { (rv[x[key]] = rv[x[key]] || []).push(x); return rv; }, {}); };
To group objects by "Phase":
const data = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, ... ]; const groupedByPhase = groupBy(data, 'Phase');
groupedByPhase will contain:
{ "Phase 1": [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, ... ], "Phase 2": [ { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, ... ] }
To group further by "Step":
const groupedByPhaseStep = _(groupedByPhase).values().map(phase => { return groupBy(phase, 'Step'); }).value();
groupedByPhaseStep will contain:
[ { "Phase": "Phase 1", "Step": "Step 1", "Value": 15 }, ... ]
The above is the detailed content of How Can I Efficiently Group an Array of Objects in JavaScript Using a Vanilla Approach?. For more information, please follow other related articles on the PHP Chinese website!