Skip to content

Instantly share code, notes, and snippets.

@pgmoir
Created May 21, 2019 12:27
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 pgmoir/9659f892bb244b2dd13c5d0c755efe1c to your computer and use it in GitHub Desktop.
Save pgmoir/9659f892bb244b2dd13c5d0c755efe1c to your computer and use it in GitHub Desktop.
Calculate depth of array
const arr = [[["blah", 876, true], [3, 23, 56], ["hjdfhkjhk", false, -1]]];
const arr1 = [["blah", 876, true], [3, 23, 56], ["hjdfhkjhk", false, -1]];
const arr2 = [[["blah", 876, true], [[98728713,918723987,1283787],3, 23, 56], [[98728713,918723987,1283787],"hjdfhkjhk", false, -1]]];
const arr3 = [[["blah", 876, true], [[98728713,[2376,81727],918723987,1283787],3, 23, 56], [[98728713,918723987,1283787],"hjdfhkjhk", false, -1]]];
const arr4 = [[["blah", 876, true], [[[[[98728713,918723987,1283787],3, [1263876,["sdhjh",[12,true,[12873,8273,128],94853],23, 56]]], [[98728713,918723987,1283787],"hjdfhkjhk"]]], false, -1]]];
const getDepthOfArray = (arr) => {
let depth = 0;
let included = [];
const checkDepth = (arr, included, level) => {
if (Array.isArray(arr)) {
depth++;
included[level] = true;
checkDeeper(arr, included, level+1)
}
};
const checkDeeper = (arr, included, level) => {
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
if (!included[level]) {
depth++;
included[level] = true;
}
checkDeeper(arr[i], included, level+1);
}
};
};
checkDepth(arr, included, 0);
return depth;
}
console.log(getDepthOfArray(arr));
console.log(getDepthOfArray(arr1));
console.log(getDepthOfArray(arr2));
console.log(getDepthOfArray(arr3));
console.log(getDepthOfArray(arr4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment