Get array's depth in JavaScript

前端 未结 6 2055
慢半拍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

    You can use a recursive function:

    function getArrayDepth(obj) {
        if (Array.isArray(obj)) return 1 + Math.max(...obj.map(t => getArrayDepth(t)))
        else return 0
    }
    
    
    console.log(getArrayDepth([1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]))
    console.log(getArrayDepth([1,[1]]))

提交回复
热议问题