Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda