Get array's depth in JavaScript

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

    This one is a bit easier to understand, if you'd like.

    var array = [
    [0, 1],
    [1, 2, 3, [1, 0]],
    [2, 3, [1, 2, [5]]],
    [1, [6, 3, [1, 2, [1, 0]]]],
    [2]
    ]
    
    function depth(array, rec) {
    if (!Array.isArray(array)) throw new Exception('not an array');
    
    var res = rec;
    for(var i = 0; i < array.length; ++i) {
        if (Array.isArray(array[i])) {
        var subDepth = depth(array[i], rec + 1);
        if (subDepth > res) {
            res = subDepth;
        }
      }
    }
    return res;
    }
    

提交回复
热议问题