What is the best way to determine the number of dimensions in a JavaScript array?

Take a look at this array and its corresponding expected output:

In Javascript, is it possible to dynamically determine how many levels there are in the array ary?

var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]];
Output: 3

var ary = ["a","b",["c","d"],"e",["f","g","i"]];
Output: 2

var ary = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];
Output: 4

Answer №1

Below is a recursive function designed to navigate through the layers of an array while keeping track of its maximum depth. It's worth noting that this function utilizes properties attached to itself for tracking purposes.

var arr = ["a","b",["c",["d"]],"e",[["f","g",["i","j"]],"k"]];

function calculateMaxDepth(arr, start) {

  //Attach depth-related properties to the function
  if (start){
    calculateMaxDepth.depth = 0;   
    calculateMaxDepth.maxDepth = 0;   
  }
    
  //Determine and keep track of max depth
  calculateMaxDepth.depth++
  if (calculateMaxDepth.depth > calculateMaxDepth.maxDepth)
    calculateMaxDepth.maxDepth++;  

  //Recursively handle each element in the array
  for (let element of arr)
    if (element instanceof Array)
       calculateMaxDepth(element);

  calculateMaxDepth.depth--;  
  
  //Return max depth upon reaching initial level again
  if (calculateMaxDepth.depth === 0)
     return calculateMaxDepth.maxDepth;  
}

let result = calculateMaxDepth(arr, true);
console.log(result);

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

The definition of require is missing in the MEAN stack node

Currently experimenting with building an application on the MEAN stack and encountered a hurdle involving the use of Node's require function. Here is my current project structure: -- app -- images -- scripts -- app.js // configuration fi ...

retrieve data types from an array of object values

I am looking to extract types from an array of objects. const names = [ { name: 'Bob' }, { name: 'Jane' }, { name: 'John' }, { name: 'Mike' }, ] The desired result should resemble thi ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...

Link that causes the regular expression test to hang

My goal is to create a regular expression that can accurately identify URLs. I found the code snippet for this on Check if a Javascript string is a url. The code looks like this: function ValidURL(str) { var pattern = new RegExp('^(https?:\/&b ...

What causes useEffect to run twice in React and what is the best way to manage it effectively?

I'm currently facing an issue with my React 18 project where the useEffect hook is being called twice on mount. I have a counter set up along with a console.log() inside the useEffect to track changes in state. Here's a link to my project on Code ...

Struggling to set up the connection between React-Redux connect and the Provider store

Currently utilizing Redux with React Native for state management. I've set up the store and Provider successfully it seems, as I can utilize store.getState() and store.dispatch(action()) from any component without issue. However, I'm encountering ...

Choosing to maintain an open server connection instead of regularly requesting updates

Currently, I am in the process of developing an innovative online presentation tool. Let's dive into a hypothetical situation: Imagine one person is presenting while another connects to view this presentation. >> How can we ensure that the viewer&ap ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

Tips for extracting a value from a mongodb aggregate operation

I am attempting to retrieve a value from a MongoDB aggregate in order to display it on an EJS page using the totalAmount variable. The result I am currently receiving is [{"totalAmount":42}] and my goal is to extract only the number, in this case, 42. My ...

Is there a way to simulate a click event within a Jasmine unit test specifically for an Angular Directive?

During the implementation of my directive's link function: $document.on('click.sortColumnList', function () { viewToggleController.closeSortColumnList(); scope.$apply(); }); While creating my unit test using Jasmine: describe(&apo ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

Converting DateTime to text in PHP

I'm facing a challenge where I need to separate my datetime value (stored in database) using PHP. $temps[0]['Date_deb']; // --> "2017-10-07 00:00:00" $letemps = $temps[0]['Date_deb']; //echo $letemps->format(&a ...

Using NodeJS to retrieve the mean price from the OPSkins pricelist

Is there a way to calculate the average price of every skin listed in this document? I'm wondering how one would go about using the dates and prices in order to determine the 60-day average price. My approach would involve extracting the data from t ...

Differences between Array and Database Search

Currently, I have implemented a system where I store a refresh token in a JavaScript array as well as in each user's information table. When a user requests data, I first check the token in the array. If the token matches one in the array, I loop thro ...

Why is this loop in jQuery executing twice?

$(document).bind("ready", function(){ // Looping through each "construct" tag $('construct').each( alert('running'); function () { // Extracting data var jC2_events = $(this).html().spl ...

Having trouble with installing create-react-app for my_app using npm because it seems to be stuck on f

I've hit a roadblock while trying to create a react app on my 2011 MacBook Pro. To start, I downloaded the latest version of Node from their official website. Following the instructions from React documentation, I ran the following commands: npm uni ...

Using Vue.js to handle asynchronous functions with undefined variables

My Vue.js application is facing a problem where an async function is passing a variable as undefined even though it's properly defined before the function call. The async function FETCH_DATA in my Vue.js application is defined like this: async [FETCH ...

How to choose elements using jQuery according to their CSS properties?

Seeking a solution to a unique challenge I've encountered. The website I frequent has found a way to bypass my uBlock extension by using a script that generates random element classes, such as: <div class="lcelqilne1471483619510ttupv"></div& ...