Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
节点中的算法优化,Javascript_Javascript_Arrays_Node.js_Algorithm - Fatal编程技术网

节点中的算法优化,Javascript

节点中的算法优化,Javascript,javascript,arrays,node.js,algorithm,Javascript,Arrays,Node.js,Algorithm,给定以下json数组 constgroups=[{id:1,parent:null,groupName:'Others',maxScore:3}, {id:2,父项:null,groupName:'Group 1',maxScore:0}, {id:3,父项:2,组名:'Others,maxScore:2}, {id:4,父:2,组名:'subgroup1',maxScore:1}] 在父母之间求和最大分数时,哪种更注重表现的方法更合适? 它看起来像一个树结构,但节点没有对其子节点的引用 我正在

给定以下json数组

constgroups=[{id:1,parent:null,groupName:'Others',maxScore:3},
{id:2,父项:null,groupName:'Group 1',maxScore:0},
{id:3,父项:2,组名:'Others,maxScore:2},
{id:4,父:2,组名:'subgroup1',maxScore:1}]

在父母之间求和最大分数时,哪种更注重表现的方法更合适? 它看起来像一个树结构,但节点没有对其子节点的引用

我正在尝试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;
    });
}
预期结果将是

constgroups=[{id:1,parent:null,groupName:'Others',maxScore:3},
{id:2,父项:null,groupName:'Group 1',maxScore:0,maxPosibleScore:3},
{id:3,父项:2,组名:'Others,maxScore:2},
{id:4,父:2,组名:'subgroup1',maxScore:1}]

使用迭代。通过使用(或)克隆对象,为每个对象创建一个新条目(如果是父对象,则更新现有条目)

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

使用转换回数组

const groups=[{id:1,父组:null,groupName:'Others',maxScore:3},{id:3,父组:2,groupName:'Others',maxScore:2},{id:4,父组:2,groupName:'group1',maxScore:1},{id:2,父组:null,groupName:'group1',maxScore:5}];
常数ms='maxScore';
常量mps='maxPossibleScore';
常量结果=对象值(组)减少((r,o)=>{
//克隆
常数c={…o};
//如果之前初始化了当前父级,请更新maxPossibleScore
如果(!o.parent&&r[o.id])c[mps]=r[o.id][mps]+c[ms];
r[o.id]=c;
if(o.parent){
//如果父项不存在,则初始化
r[o.parent]=r[o.parent]| |{};
//如果parent.maxPossibleScore不存在,则初始化它
如果(!(r[o.parent]中的mps){
r[o.parent][mps]=r[o.parent][ms]|0;
}
r[o.parent][mps]+=o[ms];
}
返回r;
}, {}));

console.log(结果)
问最好的问题……是非常主观的。什么对一方最好可能对另一方不好。你可以使用jsPerf或类似的网站/工具测试有效的方法/解决方案的性能/给出正确的结果,并使用最适合你的场景的方法。-如果你还没有有效的解决方案,那么请将问题重新表述为相反,请关注这一点。它实际上是有效的,但我认为它可以根据我需要映射的次数进行优化。减少以获得正确的结果。如果您的代码有效,并且您正在寻找优化,则可能会得到更好的答案,因为这些类型的问题通常与Stackoverflow主题无关。请查看哪些问题和哪些问题存在问题为什么?OP确实要求提供性能更好的代码,为什么您的代码要比OPs现有的代码性能更好?您是如何确定的?jsPerf或类似的?大O符号-O(n)与至少O(n^2)(当前解决方案)。因为我们使用的是调用回调函数的reduce,所以它的性能不如简单的for循环。@OriDrori,它不是wokring:(如果我只有一个parent=null,它的maxPosibleScore保持为0,现在应该修复。如果没有,请在注释中添加一个测试用例。