Let’s write a function deepOnlyIntegers that returns an array, removing all non-integers, no matter how deeply the array is nested.

Traversing the Array

Let’s begin by traversing the array

Then, we know we’re returning a new array so let’s add that.

Checking for Arrays with Head

Then our logic forks into two possibilities.

Either the value we’re checking is an array

Or it isn’t.

Let’s add that check.

Let’s first investigate the case where head is not an array. If head is not an array, then our logic forks into two additional possibilities.

head is either an integer and we want to include in our new array

or a non-integer and we want to exclude it

We know how to add values to our array from the last post, so let’s build our array by concatenating head with deepOnlyIntegers(tail)

What happens in our function so far? It finds 1, which is an integer, so it concatenates 1 with the head of the tail, the value [[2],"not me"]. Now we have an array case, which we haven’t accounted for, and it returns undefined. We haven’t told our function to keep checking the array so it simply returns. It concatenates undefined with 1 and returns [1, undefined].

Not exactly what we wanted. Let’s account for the array case.

What would happen if we used our normal way of building arrays?

Well, now we get the entire original array. Getting closer, but not there yet.

Recurring with Head

In the case that head is an array, we recur with head.