javascript - 查找作为该对象的直接或间接子对象的对象数量的有效方法是什么

标签 javascript arrays performance object javascript-objects

JavaScript 对象数组,例如: 让对象数组 =

[
{ id: 0, parentId: null}, 
{ id: 4, parentId: 3},
{ id: 1, parentId: 0}, 
{ id: 3, parentId: 2},
{ id: 2, parentId: 0}
]

其中,parentId 当不为 null 时,引用数组中 id =parentId 的另一个对象。这些对象形成了一种可以像树一样可视化的关系:

enter image description here

我们必须在 JS 中创建一个函数,给定一个 id,返回该对象的直接或间接子对象的数量。例如,如果函数被赋予值 3,则应返回 1,如果函数被赋予值 0,则应返回 4。

我尝试过的,

var count = 0;
var selected = [];

let objectArray = [
      { id: 0, parentId: null},
      { id: 4, parentId: 3},
      { id: 1, parentId: 0},
      { id: 3, parentId: 2},
      { id: 2, parentId: 0}
];


var factorial = function(objectArray, selected, num) {
  // console.log('5 - Array = ', Array );
  console.log('6 - selected = ', selected );
  // do stuff here

  for (var i = 0; i < objectArray.length; i++) {
    console.log('19 -  num = ', num );
    console.log('20 -  i =', i, objectArray[i] );
    console.log('21-  parent_id =', i, objectArray[i].parentId  );

    if ( objectArray[i].parentId  === num ) {
        console.log('   yes with num =', num );
        count = count + 1;
        selected.push(objectArray[i]);

        // selected.pop(selected[i]);

        console.log(' 18-  count = ', count );
    }
    console.log('20 ============ done =========== i= ', i );

    console.log(' ============ selected ==== ', selected );
    console.log('25 ============ count =========== ', count );
  }


  // if (selected.length >= 0 ) { // terminal case
  if ( selected.length == 0 ) { // terminal case
  // if ( count >= 6 ) {
    console.log('29-  %%%%%%%%%%%% if selected.length =', selected.length);
    console.log('29-  %%%%%%%%%%%% if  count %%%%%%%%% ', count );
    return count;
  } else { // block to execute
    console.log(' ****** in else --  now calling Selected Arr ******');


    for (var i = 0; i < selected.length; i++) {
        console.log(  '52-  selected[i].id  =',  selected[i]  );
      factorial (objectArray, selected, selected[i].id  );
    }

    // return ( factorial (objectArray, selected, num ));
  }

};



factorial(objectArray, selected, 0);

最佳答案

您可以尝试这种方法,从给定对象创建 map 并添加父级和子级。从结果对象中找到 childCount 如下:

var rels = [
{ id: 0, parentId: null}, 
{ id: 4, parentId: 3},
{ id: 1, parentId: 0}, 
{ id: 3, parentId: 2},
{ id: 2, parentId: 0}
];

 // create a map of nodes
 var nodeMap = distinct(rels);
 nodeMap = graph(rels,  nodeMap); // update parent and children

 childCount(3, nodeMap);
 childCount(0, nodeMap);

function distinct(nodes){
     return nodes.reduce(function(prev, curr){
          prev[curr.id] = {id:curr.id, parent:null, children:[]}
      return prev;
    }, {});
}

function graph(nodes, nodeMap){
    nodes.forEach(function(node){       
       if (node.parentId !== null) {        
           var parentNode = nodeMap[node.parentId]
           var childNode = nodeMap[node.id];

           console.log(parentNode, childNode)

           childNode.parent =  parentNode;
           parentNode.children.push(childNode);
       }
      });

   return nodeMap;
 }

 function childCount(id, nodeMap){
    var node = nodeMap[id];

    console.log('cc', id, node);

    return  node.children.reduce(function(prev, curr){ 
                         return prev + childCount(curr.id, nodeMap) 
                 }, 
                 node.children.length);
 }

关于javascript - 查找作为该对象的直接或间接子对象的对象数量的有效方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48273527/

相关文章:

c++ - 这段代码会在每次迭代时获取元素吗?

performance - Scala集合转换性能: single looping vs.多重循环

javascript - 当 console.logging 组件内的窗口对象时,它给出 'undefined' 。但使用浏览器控制台时可以访问

javascript - 在 Laravel 中将 JavaScript 作为外部脚本运行

arrays - Swift-在不同的类中使用数组

c# - 如何在 C# 中通过 TCP 连接发送整数数组

java - 有 Intent 地在 2 个 Activity 之间传递数组

php - 在 PHP 7 的 foreach 中通过引用传递值对性能真的有用吗

javascript - 时间序列数据的堆积面积图

javascript - 类似 Facebook 的开源聊天(使用 Jabber 或 IRC)