I found a similar problem to mine on above post.
Need to get the total from the below json
const d = [
{ 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 used the solution as given in the answers
function groupBy(data, fields, sumBy='Value') {
let r=[], cmp= (x,y) => fields.reduce((a,b)=> a && x[b]==y[b], true);
data.forEach(x=> {
let y=r.find(z=>cmp(x,z));
let w= [...fields,sumBy].reduce((a,b) => (a[b]=x[b],a), {})
y ? y[sumBy]=+y[sumBy]+(+x[sumBy]) : r.push(w);
});
return r;
}
However I need to achieve the below result for my purpose. Not sure how to achieve this.
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1, Task 2", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1, Task 2", Value: "35" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1, Task 2", Value: "55" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1, Task 2", Value: "75" }