Algorithmseasy
Implement Array.prototype.flat
Implement `flat(arr, depth)` that flattens a nested array to the given depth. Also implement `Array.prototype.flat` on the prototype.
Asked at Meta, Amazon, Apple, TikTok
Answer
// Recursive implementation function flat(arr, depth = 1) { if (depth === 0) return arr.slice() return arr.reduce((result, item) => { if (Array.isArray(item) && depth > 0) { result.push(...flat(item, depth - 1)) } else { result.push(item) } return result }, []) } // Polyfill on Array.prototype Array.prototype.myFlat = function(depth = 1) { return flat(this, depth) } // Tests flat([1, [2, [3, [4]]]]) // [1, 2, [3, [4]]] flat([1, [2, [3, [4]]]], 2) // [1, 2, 3, [4]] flat([1, [2, [3, [4]]]], Infinity) // [1, 2, 3, 4] // One-liner alternatives const flatAlt = (arr, d = 1) => d > 0 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatAlt(v, d - 1) : v), []) : arr.slice()
Source: frontendinterviewhandbook.com