Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array's depth in JavaScript

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?

like image 594
enxaneta Avatar asked Mar 29 '19 14:03

enxaneta


1 Answers

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(0, ...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);

Edit Shoutout to Daniele Fioroni for catching an edge-case my code didn't handle: empty arrays. I've updated my code. But still, leave some upvotes over there as well.

like image 53
Thomas Avatar answered Sep 21 '22 18:09

Thomas