Discover the depth of a deeply nested array

I have a complex array structure that looks something like this: I am trying to determine the depth of this nested array, focusing on the element with the most deeply embedded children.

let arr = [
   {
     name: 'tiger',
     children: [{
       name: 'sinba',
       children: [{
         name: 'cute',
         children: []
        }]
      }]
    },
    {
      name: 'lion',
      children: []
    }
]

In this scenario, the maximum depth is 3, as the item tiger reaches a depth of 3 levels. Therefore, the depth is 3

I have attempted to solve this using recursion, but I am struggling to identify the element with the most nesting level.

Any guidance or assistance would be greatly appreciated.

Answer №1

If there are no circular references present, one approach to solve this issue is by implementing the following code:

let arr = [{
    name: 'tiger',
    children: [{
      name: 'sinba',
      children: [{
        name: 'cute',
        children: []
      }]
    }]
  },
  {
    name: 'lion',
    children: []
  }
]

function count(children) {
  return children.reduce((depth, child) => {
    return Math.max(depth, 1 + count(child.children));
  }, 0);
}

console.log(count(arr))

If circular references do exist within the data structure, the function may require adjustments to handle them appropriately. Detecting circular references can be challenging and failing to address it might lead to a "Maximum call stack size exceeded" error.

To tackle this issue without additional implementations, utilizing the native JSON.stringify function could be beneficial. This method will throw an exception only in cases where BigInt values need serialization or when cyclic objects are detected - which aligns with our requirements.

let arr = [{
  name: 'tiger',
  children: []
}]

function testCircular(arr){
  try {
    BigInt.prototype.toJSON = function() { return this.toString() }
    JSON.stringify(arr);
    return false;
  }
  catch (e) {
    return true;
  }
}

function count(children) {
  if (testCircular(children)) return Infinity;
  return children.reduce((depth, child) => {
    return Math.max(depth, 1 + count(child.children));
  }, 0); 
}

console.log(count(arr))
arr[0].children = arr;
console.log(count(arr))

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

Deleting elements from an array of objects in Angular Would you like help with

I have a JSON structure and I need to remove the entire StartGeotag object from the array. [{ CreatedDate: "2022-02-17T10:30:07.0442288Z" DeletedDate: null ProjectId: "05b76d03-8c4b-47f4-7c20-08d9e2990812" StartGeotag: { ...

Step-by-step guide on utilizing the material-ui AutoComplete feature to filter a table by selecting a key from a list and manually entering

I'm working on developing a filtering system similar to the AWS Dashboard, where users can select a filter key like instance state, which then displays the key in the input field and allows the user to enter a value to search for. I'm attempting ...

The PHP file on the server is missing the mandatory "event" parameter for the EventSource

Explaining this issue was a bit of a challenge. I've set up a Javascript EventSource object with some customized event handlers like so: var source = new EventSource('updates.php'); source.addEventListener('add', addHandler, fals ...

Utilizing React to invoke the filter method on Object.keys

A specific React component receives a state property that consists of nested objects: { things: { 1: { name: 'fridge', attributes: [] }, 2: { name: 'ashtray', ...

Access any nested node within a JSON/JS object by specifying the key's value

After spending hours searching on various forums for a solution to my problem, I have yet to find one that directly addresses the issue I am facing. So, please take a moment to review the details below. The object structure in question is as follows: let ...

Customizing the Zoom Control Style in Vue Leaflet

I'm currently working on developing a Map App in Dark Mode using Vue, but I've encountered an issue with changing the style of the Zoom Control. Here's what I have tried so far: template> <div class="main-map"> <l ...

Contrasting images showcasing Headless vs Non Headless settings in Puppeteer

I'm currently attempting to capture a screenshot or PDF of the content available at this URL. When using the option {headless: false}, the screenshot is generated correctly; however, in headless mode, some images do not render in the screenshot (for e ...

Establishing a secondary setTimeout function does not trigger the execution of JQUERY and AJAX

// Custom Cart Code for Database Quantity Update $('.input-text').on('keydown ' , function(){ var tr_parent = $(this).closest("tr"); setTimeout(function () { $(tr_parent).css('opacity', '0.3'); }, 4000); var i ...

Retrieving PokéAPI image information

My goal is to display images from the PokéAPI on my app's homescreen when it is opened. However, I am facing a challenge where I need to call 30 different APIs in order to show 30 images. Calling these APIs one after another every few seconds seems l ...

Concealing a Column within a Hierarchical HTML Table

Can anyone guide me on how to hide multiple columns using jQuery with the ID tag? I've tried implementing it but it doesn't seem to work. I also attempted to switch to using Class instead of IDs, but that didn't solve the issue either. Any h ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...

Interactive feature on Google Maps information window allowing navigation to page's functions

Working on an Angular2 / Ionic 2 mobile App, I am utilizing the google maps JS API to display markers on a map. Upon clicking a marker, an information window pops up containing text and a button that triggers a function when clicked. If this function simpl ...

The res.send() method in Restify was not triggered within the callback function of an event

Currently, I am utilizing restify 2.8.4, nodejs 0.10.36, and IBM MQ Light messaging for a RPC pattern. In this setup, when the receiver has the result ready, it emits an event. The below restify POST route is supposed to capture this event along with the ...

What is the reason for create-react-app initializing twice?

After creating a react app using the command npx create-react-app, I encountered an issue: import React from 'react'; class Costly { constructor() { console.log('creating costly class'); } } function App() { const costlyRef ...

Is it possible to interchange rows and columns in a 2D structured array?

I'm looking for a way to interchange both the columns and rows of a 2D struct array. Currently, I have code that can switch rows like this: #define N 9 typedef struct { char value; bool editable; } CELL; int main(){ CELL **grid = (CELL * ...

Troubleshooting MaterialUI Datatable in Reactjs: How to Fix the Refresh Issue

Currently, I am facing an issue with rendering a DataTable component. The problem is that when I click on the "Users" button, it should display a table of Users, and when I click on the "Devices" button, it should show a table of Devices. But inexplicably, ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

Having Trouble with Your React.js Rendering?

I'm starting to learn React.js but I'm having trouble rendering it into the HTML. I can't figure out what's wrong. Any help would be greatly appreciated. Below are the HTML and JSX code: (Note: Full links to the react library are incl ...

Executing functions with directive controllers

Is there a simple way to call a function on a directive controller by accessing the instance using its id from the parent controller? <my-directive id="id1" /> var dirController = getDirectiveByID("id1"); dirController.someFunc(); If you have any ...