Skip to content
Advertisement

Get array’s depth in JavaScript

In order to get the array’s depth I thought I can use the flat() method like so:

JavaScript

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

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement