Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!