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

Automating the selection of a drop down based on a condition in Angular 2: A step-by-step guide

I'm facing an issue with a drop-down menu where no default value is selected. On my homepage, I need to automatically select an option based on query parameters. I've attempted various methods but none have been successful. Below is the code snip ...

Enhance your bookmarking experience with Vue mixins that allow you to easily customize the color

Looking for a way to efficiently bookmark pages in my application, I have successfully implemented a feature where I can add pages by their name and URL into bookmarks. Upon clicking the bookmark button, it changes color to indicate that the page has been ...

JavaScript: Modifying an Array of Matrices

Could anyone assist me with updating a matrix array? I have an initial matrix with preset values and need to update specific coordinates within it. Here is the base matrix: var myMatrix = [ ['-','-','-','-',&ap ...

Struggling to Implement Insertion Sort with JSON Data

public class ReverseList extends HttpServlet { public static void sort(int arr[]) { int N = arr.length; int i, j, temp; for (i = 1; i< N; i++) { j = i; temp = arr[i]; while (j > 0 && temp &l ...

Tips for dynamically inserting JSON data into HTML elements

{ "top10": [ { "state": "red", "claimed": true, "branch": "release-2.3.4", ...

The Click Event is failing to trigger for a dynamically created ID within a span element

I am currently working on a Task Project. In this project, I have been adding items dynamically and generating items dynamically as well. However, when it comes to deleting items by clicking on a span element, the click event doesn't seem to work. I ...

Changing styles with the use of bootstrap.css themes on the fly

I'm experimenting with toggling between a custom dark and light theme in my MVC application. On the _Layout.cshtml page, the default theme is loaded by the following code: <link id="theme" rel="stylesheet" href="~/lib/bootstrap/dist/css/Original. ...

Alter the Default Visibility on an HTML Page from Visible to Hidden with JavaScript

I found this code snippet on a website and made some modifications. On my webpage, I have implemented links that toggle the visibility of hidden text. The functionality is working fine, but the issue is that the hidden text is initially visible when the p ...

Count the number of distinct values in an array of objects

Could you assist me with a JavaScript problem I'm experiencing? I have an array and need to extract the count key from the response. Here is a sample response: var events = [ ... I would like the array response to look like this: var events = [ ... ...

Setting a default value for NULL property in TypeScript

Trying to establish a default value for all NULL objects has been quite the challenge. The current code looks like this: private setDisplayAmount(summaries: summary[]): void { summaries.map(t => { // performing some operations, and then... ...

Every time I invoke a module, non-global variables are utilized

Within a module.exports file, I am facing an issue where the variables are shared among different instances of the module. Instead, I want each call to the module to have its own set of values for cycle number, original data, new product, etc., similar to ...

Discover the basics of incorporating libraries using npm

As a beginner in JavaScript, I am looking to incorporate moment.js or another library into my project. However, I am unsure of how to properly set up my project so that I can import from the library. Here is how I have structured my HTML: <!DOCTYPE html ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

Issue: The variable THREE has not been defined within the FBXLoader code

Currently, I am utilizing the module version of three.js in order to execute imports from a client-side JavaScript file structure. The core functionality of THREE is working correctly. However, I am encountering an issue when attempting to use it with FBX ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn' ...

Establishing a minimum width for the value of zero in AmCharts column series by customizing the bullet labels

Here's an interesting example where I have arranged column series with bullet labels. However, you may notice that there are some 0 values present as well. My goal is to establish a minimum width for the series so that even if the value is small or 0, ...

Unable to use jQuery to delete class from an element

Here is the markup I am working with: <div class="row"> <img src="image.png" class="download-image regular-image" /> <div class="options"> <p>download</p> </div> <img src="image.png" class="download-image r ...

What is the best way to customize multiselection in jqgrid?

jQuery("#grid").jqGrid({ datatype: "local", width:'auto', height: 'auto', multiselect:true, colNames:[ 'no' ], colModel:[ {name:'no', align:'r ...

Encountered an error while trying to create a new NestJS project using yarn: Command execution failure - yarn install --

Having trouble installing a new NestJs project using yarn. Operating system : Microsoft Windows [version 10.0.19044.3086] Node version : 18.17.1 npm version : 9.6.7 yarn version : 1.22.19 Nest cli version : 10.1.16 I attempted to install by running : npm ...

Expanding Text Area in AngularJS

I came across this directive and I want to integrate it into my project, but I need the text area to expand as soon as the content is loaded. Angular-Autogrow.js: (function(){ 'use strict'; angular.module('angular-autogrow', [ ...