How do I write this recursive function to find the max depth of my object?

前端 未结 6 1697
庸人自扰
庸人自扰 2020-12-06 14:30

I\'m trying to write a function that will loop through my object and return the level depth of the object.

For example, if I ran the function on this object:

6条回答
  •  眼角桃花
    2020-12-06 14:59

    I have changed your code a bit to work as you want it to:

    function getDepth(node, depth = 0) {
        if (!!node.children && node.children.length > 0) {
            var childDepths = [];
            depth++;
    
            for (var i = 0; i < node.children.length; i++) {
                childDepths.push(getDepth(node.children[i]));
            }
            return depth + Math.max(...childDepths);
        }
    
        return depth;
    }
    
    var depth = getDepth(root);
    
    console.log('currentMaxDepth', depth);
    console.log('root', root);
    

    The trick is to measure depths of siblings on the same level and than pick the deepest of them. Here's also a jsfiddle: https://jsfiddle.net/2xk7zn00/

提交回复
热议问题