Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Implement Array Flat (Main Thread)

Here is the interview question prompt, presented for reference.

In Javascript there is a method for flattening an array that can be invoked by calling the function flat(array, depth). This function works in such a way that it reduces the nesting of a given array, by creating a new array with all sub-array elements concatenated into it recursively up to the given depth level.

This means that if there are multiple nested arrays inside a given array, it would return an array containing only the elements of the main array itself, and the elements from the nested arrays that are placed inside the given depth level.

Here is an example of what this method does:

array = [1, [2], [3, [4]]];
flat(array, 1)
// [1, 2, 3, [4]] flattens on depth level 1
flat(arr, 2)
// [1, 2, 3, 4] flattens on depth level 2

Can you implement your own version of this method, that will receive two parameters: an array, and an integer for the depth level, and would have the following structure:

function flat(array, depthLevel = 1) {
    let result = [];
    // your implementation here
    return result;
}

![cover](https://storage.googleapis.com/algodailyrandomassets/curriculum/frontend/interview-questions/implement-array-flat.jpg)

You can see the full challenge with visuals at this link.

Challenges • Asked over 3 years ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Jun 04, 2022:

This is the main discussion thread generated for Implement Array Flat (Main Thread).