Get array’s depth in JavaScript

I think a recursive approach is simpler. If your current item is an Array determine the max depth of its children and add 1.

function getArrayDepth(value) {
  return Array.isArray(value) ? 
    1 + Math.max(0, ...value.map(getArrayDepth)) :
    0;
}



let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]

console.log(testRy);

console.log(getArrayDepth(testRy))

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.

Leave a Comment