Mark As Completed Discussion

Solution

We can easily implement this method as a recursive function that will iterate over each element of the array, and check if that element is an array. As we said before, an element of the input array can be either a normal object, or an array that is nested and needs to be flattened.

If the element is a array, we will call the method recursively for that array, reducing the depthLevel by one. This way, we would start from the top level, and work our way into the lower depth levels until we reach the given depth level, while filling the resulting array with the necessary elements.

Otherwise, if the item itself is not an array, we would consider it being an element of the given array, will directly push it into the resulting array, and continue looping the following elements of the given array, to check if any nested ones are left.

This being said, our final solution would look like this:

JAVASCRIPT
1function flat(array, depthLevel = 1) {
2    let result = [];
3    array.forEach((item) => {
4        // if the item of the main array is an array itself, call the method recursively 
5        // to check the elements inside
6        if (Array.isArray(item) && depthLevel > 0) {
7            result.push(...flat(item, depthLevel - 1));
8        } else result.push(item); // else, push the object into the result
9    });
10    return result;
11}