Given the following json array
const groups=[{ id:1, parent:null, groupName:'Others', maxScore:3},
{id:2, parent:null, groupName: 'Group 1', maxScore:0},
{id:3, parent:2, groupName:'Others, maxScore:2},
{id:4, parent:2, groupName:'Sub Group 1', maxScore:1}];
What would be a more performance oriented approach to sum maxScores within parents ? It looks like a tree structure, but nodes don't have references to their children.
Im trying a map.reduce approach right now
function addMaxScoreToGroups(groups) {
return groups.map((group) => {
const newGroup = group;
if (group.parent === null && group.name !== 'Others') {
const children = groups.filter(elem => elem.parent === group.id);
if (children) {
newGroup.maxScore = children.map(x => x.maxScore)
.reduce((value, acum) => value + acum);
}
}
return newGroup;
});
}
Expected result would be
const groups=[{ id:1, parent:null, groupName:'Others', maxScore:3},
{id:2, parent:null, groupName: 'Group 1', maxScore:0,maxPosibleScore:3},
{id:3, parent:2, groupName:'Others, maxScore:2},
{id:4, parent:2, groupName:'Sub Group 1', maxScore:1}];