This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.
AI solution for JavaScript Coding Question on BFE.dev
3. implement Array.prototype.flat()
Recursive solution:
function flat(arr, depth = Infinity) { const flattened = []; for (const element of arr) { if (Array.isArray(element) && depth > 0) { flattened.push(...flat(element, depth - 1)); } else { flattened.push(element); } } return flattened;}
Iterative solution:
function flat(arr, depth = Infinity) { const flattened = []; const stack = [...arr]; while (stack.length) { const next = stack.pop(); if (Array.isArray(next) && depth > 0) { stack.push(...next); depth--; } else { flattened.unshift(next); } } return flattened;}
Note: The iterative solution produces a reversed flattened array, hence the use of unshift
to maintain order.