Implement Array.flat (Medium)
Good evening! Here's our prompt for today.
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:
1array = [1, [2], [3, [4]]];
2flat(array, 1)
3// [1, 2, 3, [4]] flattens on depth level 1
4flat(arr, 2)
5// [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:
1function flat(array, depthLevel = 1) {
2 let result = [];
3 // your implementation here
4 return result;
5}

xxxxxxxxxx
function flat(array, depthLevel = 1) {
let result = [];
array.forEach((item) => {
// if the item of the main array is an array itself, call the method recursively
// to check the elements inside
if (Array.isArray(item) && depthLevel > 0) {
result.push(flat(item, depthLevel - 1));
} else result.push(item); // else, push the object into the result
});
return result;
}