Flatten the Array
You are required to implement a custom Array.prototype.flat
function.
This function creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
// Input
const arr1 = [0, 1, 2, [3, 4]];
// Output
const res = flat(arr, 1);
console.log(res); // [0, 1, 2, 3, 4]
Solution
function flat(arr, depth = 1) {
if (depth === 0) return arr;
const result = [];
for (const item of arr) {
if (Array.isArray(item)) {
result.push(...flat(item, depth - 1));
} else {
result.push(item);
}
}
return result;
}
const test = [1, 2, [3, 4, [5, 6], 7, 8], 9];
console.log(flat(test, 2)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)