What is the most efficient way to group objects in an array?
For example, given this object array:
[ { 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" } ]
I am displaying this information in a table. I want to group by different methods but I want to sum the values.
I'm using Underscore.js for its groupby functionality, which helps a lot but doesn't solve the whole problem because I don't want them to "split" but "merge", more like SQLgroup by
method.
I'm looking to be able to calculate the sum of specific values (if needed).
So if I execute groupbyPhase
, I expect to receive:
[ { Phase: "Phase 1", Value: 50 }, { Phase: "Phase 2", Value: 130 } ]
If I execute groupyPhase
/Step
, I receive:
[ { Phase: "Phase 1", Step: "Step 1", Value: 15 }, { Phase: "Phase 1", Step: "Step 2", Value: 35 }, { Phase: "Phase 2", Step: "Step 1", Value: 55 }, { Phase: "Phase 2", Step: "Step 2", Value: 75 } ]
Is there a useful script, or should I stick with Underscore.js and loop through the result objects to calculate the total myself?
Using ES6 Map object:
About the map:https://developer.mozilla.org/en-US /docs/Web/JavaScript/Reference/Global_Objects/Map
If you want to avoid using an external library, you can simply implement the plain version of
groupBy()
like this: