In order to get the array’s depth I thought I can use the flat()
method like so:
JavaScript
x
26
26
1
function getArrayDepth(ry){
2
// number of levels: how deep is the array
3
let levels = 1;
4
// previous length
5
let prev_length = 1;
6
// current length
7
let curr_length = ry.length;
8
//if the resulting array is longer than the previous one add a new level
9
while(curr_length > prev_length){
10
ry = ry.flat();
11
prev_length = curr_length
12
curr_length = ry.length;
13
levels ++
14
}
15
return levels;
16
}
17
18
19
20
let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]
21
22
console.log(testRy);
23
24
console.log(getArrayDepth(testRy))
25
26
console.log(testRy);
It seams it works BUT if one of the arrays inside has a length of 1
let testRy = [1, 2, [3, 4, [5, 6], 7, [8, [9] ], 10], 11, 12]
the function fails since the flattened array is as long as the previous one.
Is there a better way to get the depth of an array in javascript?
Advertisement
Answer
I think a recursive approach is simpler. If your current item is an Array determine the max depth of its children and add 1.
JavaScript
1
15
15
1
function getArrayDepth(value) {
2
return Array.isArray(value) ?
3
1 + Math.max(0, value.map(getArrayDepth)) :
4
0;
5
}
6
7
8
9
let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]
10
11
console.log(testRy);
12
13
console.log(getArrayDepth(testRy))
14
15
console.log(testRy);
Edit Shoutout to Daniele Fioroni for catching an edge-case my code didn’t handle: empty arrays. I’ve updated my code. But still, leave some upvotes over there as well.