A
A
Atheist212020-09-10 19:04:32
JavaScript
Atheist21, 2020-09-10 19:04:32

How to determine the maximum nesting of arrays in an array?

Write a function that determines the depth of the deepest nested array in an array.
Return 1 if there are no nested arrays. The array passed to your function can contain any type of data.

I am a beginner and I am trying to parse tasks into more complicated recursion, I wrote such code, but it checks the number of arrays in the array. How can I enhance my code so that it checks what is required?

function list_depth(arr) {
        let n = 1;
        for (i of arr) {
          if (Array.isArray(i)) {
            n += list_depth(i);
            console.log(n);
          }
        }
        return n;
      }
      console.log(list_depth([2.0, [2, 0], 3.7, [3, [1, 1], 7], 6.7, [6, 7]]));

And is it possible somehow without declaring the variable n inside the function?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-09-10
@Atheist21

How can I enhance my code so that it checks what is required?

Supplement - nothing. Need to rewrite. Not all the results of recursive calls should be added to one, but only one, the largest.
And is it possible somehow without declaring the variable n inside the function?

Can:
const getMaxDepth = arr =>
  Array.isArray(arr)
    ? 1 + Math.max(0, ...arr.map(getMaxDepth))
    : 0;


console.log(getMaxDepth([ 1, [ 2 ], [ [ 3 ] ], [ [ [ 4 ] ] ] ])); // 4
console.log(getMaxDepth([])); // 1
console.log(getMaxDepth(666)); // 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question