The most efficient way to group object arrays
P粉310754094
2023-08-21 14:34:06
<p>What is the most efficient way to group objects in an array? </p>
<p>For example, given the following array of objects: </p>
<pre class="brush:php;toolbar:false;">[
{ 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" }
]</pre>
<p>I am displaying this information in a table. I want to group by different methods but I want to sum the values. </p>
<p>I'm using the groupby function of Underscore.js, which is helpful, but doesn't quite satisfy the need because I don't want to "separate" them but "merge" them, more like SQL's group by method. </p>
<p>What I want is to be able to sum specific values if needed. </p>
<p>So, if I group by <code>Phase</code>, I want to get: </p>
<pre class="brush:php;toolbar:false;">[
{ Phase: "Phase 1", Value: 50 },
{ Phase: "Phase 2", Value: 130 }
]</pre>
<p>If I group by <code>Phase</code> / <code>Step</code>, I want to get: </p>
<pre class="brush:php;toolbar:false;">[
{ 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 }
]</pre>
<p>Is there a useful script that can do this, or should I just keep using Underscore.js and do the summing by looping over the result objects? </p>
Use ES6 Map object:
About 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 a native version of
groupBy()
like this: