function getDepth(arr) {
const eleDepths = []
arr.forEach( ele => {
let depth = 0
if (Array.isArray(ele)) {
depth = getDepth(ele)
}
eleDepths.push(depth)
})
return 1 + max(eleDepths)
}
function max(arr) {
return arr.reduce( (accu, curr) => {
if (curr > accu) return curr
return accu
})
}
// test
const arr1 = [1, 2, 3]
const arr2 = [1, 2, 3, [1, 2]]
const arr3 = [1, [1, [1, 2]], 3]
const arr4 = [1, [1, [1, 2]], 3, 4, [1, [1, [1, 3]]]]
console.log(getDepth(arr1)) // 1
console.log(getDepth(arr2)) // 2
console.log(getDepth(arr3)) // 3
console.log(getDepth(arr4)) // 4
原创文章,作者:普尔小编,如若转载,请注明出处:http://www.puerpx.cn/pxwd/5269.html