2

For example I have an array as follows & expected output is given.

In javascript how can we determine dynamically how many levels are there in my 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
4
  • I'd recommend writing a recursive loop that goes through each item in the array, and if it is an array recurses into that array (and so on), increasing a currentDepth and a maxDepth variable. Every time you exit a level of recursion decrement currentDepth but keep maxDepth. maxDepth is only increased if the currentDepth is greater than it. When you're done, maxDepth should be the deepest nested "dimension" in your array. Commented Aug 24, 2021 at 6:04
  • first creat var dim = 0. then iterate with for loop in every for loop check instance of Array and if it would be true add ++ to dim. Commented Aug 24, 2021 at 6:06
  • Does this answer your question? Get array's depth in JavaScript Commented Aug 24, 2021 at 6:14
  • possibly duplicate of stackoverflow.com/q/13814621/8657746 Commented Aug 24, 2021 at 6:19

1 Answer 1

2

Here is a reccursive function that will traverse through the depths of the array and track the maximum of it. Note that the tracking is done via properties attach to the function itself.

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



function getDimension(arr, start) {

  //Attach depth tracking properties to the function
  if (start){
    getDimension.depth = 0;   
    getDimension.maxDepth = 0;   
  }
    

  //Track max depth
  getDimension.depth++
  if (getDimension.depth > getDimension.maxDepth)
    getDimension.maxDepth++;  

  //Manage recursion
  for (let element of arr)
    if (element instanceof Array)
       getDimension(element);

  getDimension.depth--;  
  
  //In first level at this point
  if (getDimension.depth === 0)
     return getDimension.maxDepth;  

}

let d = getDimension(ary1, true);
console.log(d);

Sign up to request clarification or add additional context in comments.

2 Comments

It's worth noting that, because the depth is cached as a property on the function itself and it is never cleared, this will always report the max depth as the max depth of any array it has ever been passed, not necessarily the array that it has currently been passed. It essentially can't be reused.
@AlexanderNied Very true! Thanks for pointing this out. Answer edited.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.