Created
April 30, 2018 08:41
-
-
Save dhunmoon/9e54e190fc877e21f9dd15d947b1986f to your computer and use it in GitHub Desktop.
Get Depth of an array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function depthOf(arr) { | |
if(!Array.isArray(arr)) | |
throw "Not an Array" | |
var depth = 1; | |
var i; | |
for(var i = 0; i< arr.length; i++){ | |
if (!Array.isArray(arr[i])) continue; | |
if(Array.isArray(arr[i])){ | |
var depth = depthOf(arr[i]) + 1; | |
depth = Math.max(depth, depth); | |
} | |
} | |
return depth; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It there is a self-referencing object or array then this code will go into an endless loop.
In that case, we can take advantage of sets to see if there is a self-reference or not to fix the issue.