Please explain the recursive solution of finding the depth of an array

Solution 1:

First, a primer on recursion:

Recursion ultimately tries to solve the most basic form of the problem you can have and then gradually narrow down any complex problem to the most basic form. So you need the following (probably doesn't make complete sense until you read all of it):

  1. You need to solve the base case.
    • the base case also serves as a terminal condition. You want to stop calling the function recursively at some point. Once you reach the base case you don't need to recurse any more.
  2. You need a reduction step. You start with a big problem and you aim to go to the base form of it and solve it (the base case from 1.). If the current form is not the base, then it's not solvable - you need to reduce the problem a bit and call the function recursively.

So, in this case, the base case is that you get a value that is not an array. Since it's not an array, it doesn't have depth, hence you return zero. SOLVED! That is it.

However, what happens if you do get an array? Well, any array will have some depth. So, you can count one then get the contents of the array. That's the reduction step - you've reduced it from "I have an array of unknown depth" to "I have the contents of my array". When you recursively call getArrayDepth with the contents, you will re-evaluate whether you have an array or not and count appropriately. If you sum all the times you've had an array with depth of at least 1, you get the depth.

So far, we can solve the following things

Input: 42
Output (depth): 0
Why?: It's the base case - it's not an array, so we return 0 and don't recursively call the function.

Input: [42]
Output (depth): 1
Why?: We have an array ->
   count depth of 1 add the result of the recursive call with the contents 42 -->
   it's the base case - it's not an array, so we return 0 and don't recursively call the function.
Going back, we've had 0 and 1 which totals 1.

Input: [[42]]
Output (depth): 2
Why?: We have an array ->
   count depth of 1 and recursively call with the contents [42] -->
   we have an array -->
       count depth of 1 and recursively call with the contents 42 --->
       it's the base case - it's not an array, so we return 0 and don't recursively call the function.
Going back, we've had 0, 1 and 1 which totals 2.

And so on.

Now, as for why you use Math.max and Array#map. Since arrays can have many elements, you use .map to call getArrayDepth on each of them. This will cause further recursion to work it out but at the end you will get an array of all the depths of the elements, so ["a", ["b"], [["c"]]] will be transformed into [1, 2, 3]. Since you need to get the total depth, you need the highest number - this is achieved by using Math.max with spread syntax to return the maximum value.