I'm trying to solve this problem in many ways, but unable to move further.
I've a data something like this:
const dummyData = [{
metric: {
id: "A",
code: "00",
advice: "123"
},
values: [[123, 1], [332, 2]]
}, {
metric: {
id: "A",
code: "01",
advice: "123"
},
values: [[123, 5], [332, 3]]
}, {
metric: {
id: "B",
code: "01",
advice: "123"
},
values: [[123, 3]]
}]
I wanted this in 3 different formats with various group by:
Group by
id, and sum thevalues[1]For example:[{ id: 'A' values: [{ valueId: 123, value: 6 // 1 + 5 }, { valueId: 332, value: 5 // 2 + 3 }] }, { id: 'B' values: [{ valueId: 123, value: 3 }] }]Group by
idandcode, then sum thevalues[1][{ id: 'A' code: '00' values: [{ valueId: 123, value: 1 }, { valueId: 332, value: 2 }] }, { id: 'A' code: '01' values: [{ valueId: 123, value: 5 }, { valueId: 332, value: 3 }] }, { id: 'B' code: '01' values: [{ valueId: 123, value: 3 }] }]Group by
idandadvice, then sum thevalues[1][{ id: 'A' advice: '123' values: [{ valueId: 123, value: 6 // 1 + 5 }, { valueId: 332, value: 5 // 2 + 3 }] }, { id: 'B' advice: '123' values: [{ valueId: 123, value: 3 }] }]
So far I've managed to do some simple group by with a single key like this:
const a = dummyData.reduce((accumulator, currentValue) => {
(accumulator[currentValue.metric["id"]] = accumulator[currentValue.metric["id"]] || []).push(currentValue.values)
return accumulator
}, {})
Though it is not in my expected format. I know that I've to use reduce to achieve this, however I'm unable to make it work or I don't know how to do.