How to check the array is of how many dimension in javascript?

Viewed 110

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
1 Answers

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);

Related