I have an array of data in the below format
let people=[
{
aggregationType: "1",
coefficient: 0.03,
id: "p1",
name: "petter",
type: "Number",
age: 14
},
{
aggregationType: "0",
coefficient: 1,
id: "p2",
name: "mary",
type: "Number",
value: 24
},
{
aggregationType: "1",
coefficient: 0.03,
id: "p1",
name: "Amee",
type: "Number",
value: 32
},
{
aggregationType: "0",
coefficient: 1,
id: "p2",
name: "Mtp",
type: "Number",
value: 33
},
{
aggregationType: "1",
coefficient: 0.03,
id: "p1",
name: "Louis",
type: "Number",
value: 44
},
]
I want to grouped the dataset by the 'id' and check the condition: if key aggregationType = 0 then calculate sum age, if key aggregationType = 1 then calculate Avg age. And multiply by key 'coefficient' so that the desired result should be like this.
output=[
[
"p1", 0.9 // equivalent to ((14 + 32 + 44)/3)*0.03 aggregationType = 1 ==> calculate avg age,coefficient: 0.03
],
[
"p2", 57 // equivalent to (24+33)*1 = 57 aggregationType = 0 ==> calculate sum age, coefficient: 1
]
]
I tried to write this function but I don't know how to continue.
let result = {};
for ( let { id, aggregationType, value } of task )
{
result[id] = result[id] || [];
result[id].push({aggregationType, value });
}
console.log(result);
/*
// group by id
result = {
p1: [
{
aggregationType: "1",
value: 14
},
{
aggregationType: "1",
value: 32
},
{
aggregationType: "1",
value: 44
}
],
p2: [
{
aggregationType: "0",
value: 24
},
{
aggregationType: "0",
value: 33
},
]
}
*/
let newResult=[];
for (let [key, value] of Object.entries(result)) {
newResult = [key, value.reduce((a, e) => {
if (e.aggregationType === '0') {
a += e.value ;
} else {
(a += e.value) / value.length;
}
return a;
}, 0)]
}
Please help me, thank you!