Return the depth of an object with multiple properties

22 hours ago 3
ARTICLE AD BOX

The problem seemed simple...

The solution is to go through all the branches of the tree, and when you reach the end of one, update (if necessary, the value of depth.

const foo = { "name": 'John', "last_name": 'Doe', "children": [ { "name": 'Jane', "last_name": 'Doe', "children": [ // add more depth { "name": 'Caracol', "last_name": 'Donem', "children": [] } ] }, { "name": 'Carol', "last_name": 'Doe', "children": [] } ] }; function getDepth( root, level ) { if( root === null || typeof root !== 'object' ) { return 0; } if( root[ "children" ].length !== 0 ) { // if you have children, we explore each // one, with an updated level value for( let i = 0; i < root[ "children" ].length; i++ ) { getDepth( root[ "children" ][ i ], level + 1 ); } } else { // if don't have children, we update the // "depth" value if( level > depth ) depth = level; } }; depth = 1; getDepth( foo, 1 ); console.log( depth );

To understand recursion, you have to think of multiple methods that do the same thing by calling each other, let's look at a small example:

let value = a_1( 5, 3 ); // receive: value = 5, limit = 3 function a_1( value, limit ) { // modify: value = 6, limit = 2 value++; limit--; // as "limit" is greater than "0", "a_2" is called if( limit > 0 ) { return a_2( value, limit ); } // In this method (if we accept that in this strange example // it is a separate method), this line will never be executed, // since "limit" is greater than "0", but we include it // because it is really the only method else return value; } // receive: value = 6, limit = 2 function a_2( value, limit ) { // modify: value = 7, limit = 1 value++; limit--; // as "limit" is greater than "0", "a_3" is called if( limit > 0 ) { return a_3( value, limit ); } else return value; } // receive: value = 7, limit = 1 function a_3( value, limit ) { // modify: value = 8, limit = 0 value++; limit--; // as "limit" is "0", nothing is called if( limit > 0 ) { return a_8000( value, limit ); } // and now yes, this method returns "value" that is received // by "a_2" which in turn returns it to "a_1" which in turn // returns it to the original caller :) else return value; }
Read Entire Article