Skip to content

Instantly share code, notes, and snippets.

@dhunmoon
Created April 30, 2018 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhunmoon/9e54e190fc877e21f9dd15d947b1986f to your computer and use it in GitHub Desktop.
Save dhunmoon/9e54e190fc877e21f9dd15d947b1986f to your computer and use it in GitHub Desktop.
Get Depth of an array.
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;
}
@dhunmoon
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment