Get array's depth in JavaScript

前端 未结 6 2066
慢半拍i
慢半拍i 2020-12-11 08:25

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

6条回答
  •  孤街浪徒
    2020-12-11 08:37

    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(...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);

提交回复
热议问题