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

Nextjs - resolving the issue of shopping carts displaying incorrect total amounts

I am currently facing an issue with the total cart amount while building a shopping cart. The problem arises when I visit the cart page as it only displays the amount of the last item added to the cart. state = { cart: { items: [], total: 0 }, }; ad ...

Implementing the 'bootstrap tour' feature in a Ruby on Rails application

I have integrated bootstrap-tour.min.css and bootstrap-tour.min.js into my project. <script type="text/javascript" src='bootstrap-tour.min.js'></script> <link rel="stylesheet" type="text/css" href="bootstrap-tour.min.css"> Her ...

Displaying identical images repeatedly, alter just one using JQuery with each change

In the design, I have both gray and blue stars displayed multiple times on the page. What I'm trying to achieve is that when a user clicks on a gray star, it should switch to blue, and vice versa. However, the current issue I'm facing is that cli ...

Avoid causing the newline character to display

var i = 'Hello \n World' console.log(i) /* Output: Hello World */ /* Desired output: Hello \n world */ var j = 'javscr\u0012ipt' console.log(j) /* Output: javscr ipt */ /* Desired output: javscr\u0012ipt */ ...

Guide to adding and showing records without the need to refresh the webpage using CodeIgniter

Hey there! I've got a code snippet here for inserting and displaying records without refreshing the web page using AJAX and plain PHP. However, I'm not sure how to set this up using CodeIgniter. Can someone please lend a hand? Here's what I ...

Having difficulties transmitting numerical values through res.send() in express with node

Currently, I'm faced with a challenge in my express application on node.js as I attempt to retrieve the "imdb rating." movies.json [{ "id": "3962210", "order": [4.361276149749756, 1988], "fields": { "year": 2015, "title": "David and Goliath" ...

showing javascript strings on separate lines

I need assistance with displaying an array value in a frontend Angular application. How can I insert spaces between strings and show them on two separate lines? x: any = [] x[{info: "test" + ',' + "tested"}] // Instead of showing test , teste ...

Using ng-repeat to display table data in AngularJS

There is an array with 7 elements, each containing an object. The goal is to display these elements in a table with one row and 7 columns. The desired output should look like this: some label1 | some label2 | some label3 | some label4 | some label5 som ...

The TypeScript `unknown` type restricts the use of non-unknown types in function parameters

Why is there an error in this code? const x: unknown[] = ['x', 32, true]; // OK const y: (...args: unknown[]) => unknown = (xx: number) => {}; // ERROR // Type '(xx: number) => void' is not assignable to type '(...args: u ...

Dynamically fetching data with Node.js using Ajax requests

Despite my efforts to scour Google and Stack Overflow, I have been unable to find a reliable method for posting data to my Node.js server. I've noticed conflicting information on various methods, likely due to changes over time. One particular code ...

What is the significance of -= and += operators in JavaScript programming language?

I'm puzzled by the mathematical process behind this JavaScript code, which results in -11. let x = 2; let y = 4; console.log(x -= y += 9) ...

Enhancing jQuery Rating Plugin

Currently, I am working on customizing the jQuery Bar Rating System Plugin. You can view an example of the plugin by visiting this link: . The rating system on my end will resemble Example D. Rather than having the plugin based on user input, my goal is to ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

Eliminate a descendant of a juvenile by using the identification of that specific juvenile

Here is the current structure I'm working with: I want to figure out how to eliminate any field that has the id 3Q41X2tKUMUmiDjXL1BJon70l8n2 from all subjects. Is there a way to achieve this efficiently? admin.database().ref('UsersBySubjects&ap ...

Retrieving an attribute through the act of clicking a button

How can I retrieve the rel attribute value when clicking on a button with the class selector? <button class="nameClass" rel="relName">Content</button> I am attempting to achieve this by: $(".nameClass").click(function(){ // Here is where ...

Adjusting the size of several images individually with jquery

Currently, I am working on a jQuery script that enables me to resize any image by simply clicking on it. The goal is to have the ability to click on one image and resize it, then click on another image and resize it independently. Here is the code I have b ...

Each time Firebase retrieves an object, it comes back with a unique name

One query has been bothering me: const questionsRef = firebase .database() .ref('Works') .orderByChild('firebaseKey') .equalTo(this.props.match.params.id); It's functional, but the issue lies in the output: "-LDvDwsIrf_SCwSinpMa ...

What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem ...

Are your GetJSON requests failing to execute properly?

I have a code snippet that executes in a certain sequence and performs as expected. <script> $.getJSON(url1, function (data1) { $.getJSON(url2, function (data2) { $.getJSON(url3, function (data3) { //manipulate data1, data2, ...

Steps to completely eliminate all elements from an object using specific keys

I have been pondering the most efficient method to delete all elements of an object through an onClick function. The goal is for the handler to remove all elements. Despite attempts with methods like the delete keyword and filtering, clicking the clear all ...