[
{
"properties": {
"name": "Название 1",
"id": 1,
"groups": [
{
"id": 0,
"name": "Группа 1",
'well-being': 0.9
},
{
"id": 1,
"name": "Группа 2",
'well-being': 0.5
},
{
"id": 2,
"name": "Группа 3",
'well-being': 0.4
}
]
}
},
{
"properties": {
"name": "Название 2",
"id": 2,
"groups": [
{
"id": 0,
"name": "Группа 1",
'well-being': 0.8
},
{
"id": 1,
"name": "Группа 2",
'well-being': 0.3
},
{
"id": 2,
"name": "Группа 3",
'well-being': 0.8
}
]
}
},
{
"properties": {
"name": "Название 3",
"id": 3,
"groups": [
{
"id": 0,
"name": "Группа 1",
'well-being': 0.8
},
{
"id": 1,
"name": "Группа 2",
'well-being': 0.1
},
{
"id": 2,
"name": "Группа 3",
'well-being': 0.6
}
]
}
},
]
const data = arr.reduce((acc, c) => {
c.properties.groups.forEach((group) => {
if (! acc.hasOwnProperty(group.id)) acc[group.id] = [];
acc[group.id].push(group["well-being"]);
});
return acc;
}, {});
/*
{
0: [0.9, 0.8, 0.8],
1: [0.5, 0.3, 0.1],
2: [0.4, 0.8, 0.6]
} */
const avg = {};
for (let id in data) {
avg[id] = data[id].reduce((acc, c) => acc + c) / data[id].length;
}
console.log(avg); /*
{
0: 0.8333333333333334,
1: 0.3,
2: 0.6000000000000001 // 0.1 + 0.2 !== 0.3
} */
const averages = Array.from(
arr
.flatMap(v => v.properties.groups)
.reduce((acc, {id, 'well-being': value}) => {
const [count, total] = acc.get(id) ?? [0, 0];
acc.set(id, [count + 1, total + value]);
return acc;
}, new Map())
.entries(),
([id, [count, total]]) => ({id, average: total / count}),
);
console.log(averages);