gpt4 book ai didi

javascript - Node, Javascript 中的算法优化

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:10:30 24 4
gpt4 key购买 nike

给定以下json数组

const groups=[{ id:1, parent:null, groupName:'Others', maxScore:3},
{id:2, parent:null, groupName: 'Group 1', maxScore:0},
{id:3, parent:2, groupName:'其他, maxScore:2},
{id:4, parent:2, groupName:'子组 1', maxScore:1}];

parents 中求和 maxScores 的更注重性能的方法是什么?它看起来像一个树结构,但 Node 没有对其子 Node 的引用。

我现在正在尝试 map.reduce 方法

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;
});
}

预期的结果是

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:'其他, maxScore:2},
{id:4, parent:2, groupName:'子组 1', maxScore:1}];

最佳答案

Array.reduce() 迭代.通过使用 object spread 克隆对象,为每个对象创建一个新条目(或在父对象的情况下更新现有条目) (或 Object.assign()

如果对象有父对象,如果父对象不存在则创建父对象,并添加/更新maxPossibleScore

使用 Object.values() 转换回数组.

const groups=[{ id:1, parent:null, groupName:'Others', maxScore:3}, {id:3, parent:2, groupName:'Others', maxScore:2}, {id:4, parent:2, groupName:'Sub Group 1', maxScore:1}, {id:2, parent:null, groupName: 'Group 1', maxScore:5}];

const ms = 'maxScore';
const mps = 'maxPossibleScore';
const result = Object.values(groups.reduce((r, o) => {
// clone
const c = { ...o };

// if current parent initalized before, update maxPossibleScore
if(!o.parent && r[o.id]) c[mps] = r[o.id][mps] + c[ms];

r[o.id] = c;

if(o.parent) {
// if parent doesn't exist init
r[o.parent] = r[o.parent] || {};
// if parent.maxPossibleScore doesn't exist init it
if(!(mps in r[o.parent])) {
r[o.parent][mps] = r[o.parent][ms] || 0;
}

r[o.parent][mps] += o[ms];
}

return r;
}, {}));

console.log(result);

关于javascript - Node, Javascript 中的算法优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50019972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com