Answer the question
In order to leave comments, you need to log in
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]]));
Answer the question
In order to leave comments, you need to log in
How can I enhance my code so that it checks what is required?
And is it possible somehow without declaring the variable n inside the function?
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 questionAsk a Question
731 491 924 answers to any question