Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure:

-root
|
|
|-child1
 |
 |-innerChild1
 |
 |-innerChild2
|
|-child2

I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example:

    var depth = getInnerDepth(root);
    depth = 3;

In this case, the depth is 3. The root has a parent at depth 1, first degree children at depth 2, and one child (child1) with children at depth 3.

    var depth = getInnerDepth(child1);
    depth = 2;

The depth here is 2 because child1 is considered the parent, so its depth is 1. Child1 has children, hence the result being 2.

   var depth = getInnerDepth(innerChild1);
   depth = 1;

For innerChild1, the depth is 1 as it does not have any children from its perspective.

It seems like this should be implemented recursively, but I am struggling to find the best approach.

 function getInnerDepth(parent){ 
   var depth = 1; 
   if (parent.hasChildren) {
    depth++;
    parent.children.forEach(function(child){ getInnerDepth(child); }) 
   }
   return depth;
  }

This pseudo code illustrates the general idea, although it's not functional yet.

Answer №1

It is my belief that this solution will meet the requirements, assuming that the .children property is an array, as indicated by the OP's use of .forEach in their attempt:

function getInnerDepth(node) {
    if (node.hasChildren) {
        var depths = node.children.map(getInnerDepth);
        return 1 + Math.max.apply(Math, depths);
    } else {
        return 1;
    }
} 

For illustrative purposes, here is an example using the DOM (with slight modifications since children in the DOM is not truly an array):

function getInnerDepth(node) {
  if (node.children.length) {
    var depths = Array.prototype.map.call(node.children, getInnerDepth);
    return 1 + Math.max.apply(Math, depths);
  } else {
    return 1;
  }
}

document.body.addEventListener("click", function(e) {
  console.log("Depth: ", getInnerDepth(e.target));
}, false);
div:not(.as-console-wrapper) {
  padding-left: 2em;
  border: 1px solid black;
}
<div>
  Root
  <div>
    Child 1
    <div>
      Sub-child 1-1
    </div>
    <div>
      Sub-child 1-2
      <div>
        Sub-child 1-2-1
      </div>
    </div>
  </div>
  <div>
    Child 2
  </div>
</div>

Answer №2

Without clear usage instructions from the OP, I decided to provide a DOM implementation for this question.

function calculateDepth(parent){ 
   var depth = 1; 
   if (parent.children.length) {
     var childDepth = 0;
     for(var i=0; i<parent.children.length; i++){
       childDepth = Math.max(calculateDepth(parent.children[i]), childDepth);
     };
     depth += childDepth;
   }
   return depth;
}

console.log(calculateDepth(document.getElementById('root')));
<div id="root">
  <span></span>
  <ul>
    <li></li>  
  </ul>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we set up a Vue.js component before incorporating it into a template?

Currently, I am working on a Vue single file template where I need to fetch some data (a JWT token) and then use that token to make another request to a graphql endpoint. The Provider Component in my template requires the JWT Token to be set up with the ...

Prevent users from adding or removing any letters

Exploring the ACE Editor integration with AngularJS (utilizing UI-Ace). I have a question. Is it possible to limit the user's actions to: Only allow entering a predefined character (for example, ;) Prevent deletion of any characters except for the p ...

Using postMessage with an iframe is causing issues within a React application

I encountered two errors when executing the code below in my React application: try { iframe.src = applicationRoutes.href; iframe.style.width = '0px'; iframe.style.height = '0px'; iframe.style.border = '0px& ...

The local authentication feature in NodeJS Passport is experiencing issues and not functioning properly

I have integrated passportjs local for authentication. However, I am facing an issue where it always redirects to the failureRedirect without displaying any error messages. The redirect also includes the original username and password, resulting in a dupli ...

The art of controlling iframe elements with jquery

I've been researching various topics related to this issue, but I'm still unable to achieve the desired outcome. Currently, I am embedding an iframe within an HTML document like so: <iframe class="full-screen-preview__frame" id="nitseditpre ...

A space designated for numerous receivers

Is there a way to create a field that contains other elements, similar to sending messages to multiple users in a social network? https://i.stack.imgur.com/P9e24.png I attempted to understand the code for this, but it's quite complex. If anyone could ...

Encountering an issue with postman where properties of undefined cannot be read

I am facing an issue while trying to create a user in my database through the signup process. When I manually enter the data in the create method, it works fine as shown below: Note: The schema components are {userName:String , number:String , email:Stri ...

Creating a Vue application utilizing a function with an unspecified purpose

Looking to create an app with a function that is currently undefined. On the production server, there is a function called __doPostBack which I am calling from my Vue app like this: getLabel(templateName) { __doPostBack(templateName, ""); } Afte ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

Tips on how to customize/ng-class within a directive containing a template using replace: true functionality

To keep replace: true, how can ng-class be implemented on the directive below without causing conflicts with the template's ng-class? This currently results in an Angular error: Error: Syntax Error: Token '{' is an unexpected token at co ...

Tooltip remains visible even after formatting in highcharts

I have successfully hidden the datalabels with 0 values by formatting them. However, after formatting the tooltips for 0 valued data in a pie chart, there is an issue where hovering over the 0 valued portion shows a white box as shown in the picture. I hav ...

Determining the background image size of a div when the window is resized

I'm facing a problem that I can't seem to solve. I have a div with a background image. <div class="a"></div> I want to make a specific point of this background image clickable. I know I can achieve this by adding a div with a z-inde ...

The keyup event fails to trigger for the search input in datatables when ajax is being used

When loading a page with a jQuery datatable via AJAX, I am aiming to implement custom filtering when the user starts typing in the default filter provided by datatables. The custom logic needs to be applied when the keyup event is triggered. Since AJAX is ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

Vue Google Tag Manager Error: This file type requires a specific loader to be handled correctly

I have integrated "@gtm-support/vue2-gtm": "^1.0.0" in one of my Vue-2 applications, with Vue versions as below: "vue": "^2.5.2", "vue-cookies": "^1.5.4", "vue-i18n": "^8.0.0", "vue-recaptcha": "^1.1.1", "vue-router": "^3.0.1", "vue-scrollto": "^2.17.1", " ...

Can you explain the significance of this error message that occurs when attempting to execute a node.js script connected to a MySQL database?

const mysql = require('mysql'); const inquirer = require('inquirer'); const connection = mysql.createConnection({ host: "localhost", port: 8889, user: "root", password: "root", database: "bamazon" }) connection.conn ...

What is the process for retrieving a value from a Django view?

Would it be feasible to call a view from a JavaScript file using Ajax and have the view only return a specific value known as "this"? However, despite attempting this, an error occurs stating that the view did not provide an HttpResponse object, but instea ...

Redis VS RabbitMQ: A Comparison of Publish/Subscribe Reliable Messaging

Context I am working on a publish/subscribe application where messages are sent from a publisher to a consumer. The publisher and consumer are located on separate machines, and there may be occasional breaks in the connection between them. Goal The obj ...

Determine which JavaScript script to include based on whether the code is being executed within a Chrome extension

I am in the process of developing a Chrome extension as well as a web JavaScript application. I currently have an HTML container. I need the container.html file to include <script src="extension.js"> when it is running in the Chrome extension, and ...

Encountering Axios CanceledError while attempting to forward a POST request using Axios

While attempting to relay a POST request from an express backend to another backend using axios, I encountered an axios error stating "CanceledError: Request stream has been aborted". Interestingly, this issue does not arise when dealing with GET requests. ...