In order to get the array's depth I thought I can use the flat()
method like so:
function getArrayDepth(ry){
// number of levels: how deep is the array
let levels = 1;
// previous length
let prev_length = 1;
// current length
let curr_length = ry.length;
//if the resulting array is longer than the previous one add a new level
while(curr_length > prev_length){
ry = ry.flat();
prev_length = curr_length
curr_length = ry.length;
levels ++
}
return levels;
}
let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]
console.log(testRy);
console.log(getArrayDepth(testRy))
console.log(testRy);
It seams it works BUT if one of the arrays inside has a length of 1
let testRy = [1, 2, [3, 4, [5, 6], 7, [8, [9] ], 10], 11, 12]
the function fails since the flattened array is as long as the previous one.
Is there a better way to get the depth of an array in javascript?
I think a recursive approach is simpler. If your current item is an Array determine the max depth of its children and add 1.
function getArrayDepth(value) {
return Array.isArray(value) ?
1 + Math.max(...value.map(getArrayDepth)) :
0;
}
let testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]
console.log(testRy);
console.log(getArrayDepth(testRy))
console.log(testRy);
You can use a recursive function:
function getArrayDepth(obj) {
if (Array.isArray(obj)) return 1 + Math.max(...obj.map(t => getArrayDepth(t)))
else return 0
}
console.log(getArrayDepth([1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12]))
console.log(getArrayDepth([1,[1]]))
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;
}
Convert the array to string lets assume
We are given a string having parenthesis like below
“( ((X)) (((Y))) )”
We need to find the maximum depth of string, like 4 in above example. Since ‘Y’ is surrounded by 4 balanced parenthesis.
Take two variables max and current_max, initialize both of them as 0.
Traverse the string, do following for every character
a) If current character is ‘(’, increment current_max and
update max value if required.
b) If character is ‘)’ means we previously had a ‘(’ character
so decrement current_max without worry but dont reduce max value .
If current_max is greater than max then update max value to current_max at that instance. after traverse is completed the max is is the depth of the array.