Array.prototype.flat
JS Functions
Medium
15 min
arrays
polyfills
recursion
Implement Array.prototype.myFlat(depth), a polyfill for the native Array.prototype.flat. It returns a new array with nested arrays spread into it, up to depth levels deep.
The starter attaches the function to Array.prototype and default-exports it.
[1, [2, [3, [4]]]].myFlat(); // [1, 2, [3, [4]]] (depth defaults to 1)
[1, [2, [3, [4]]]].myFlat(2); // [1, 2, 3, [4]]
[1, [2, [3, [4]]]].myFlat(Infinity); // [1, 2, 3, 4]
[1, [2]].myFlat(0); // [1, [2]] (a shallow copy)
[1, , [2, , 3]].myFlat(); // [1, 2, 3] (holes are removed)
Requirements
depthdefaults to1when it isundefined. Otherwise it is converted like the native method does:Number(depth),NaNbecomes0, truncated toward zero. A depth of0or below flattens nothing.Infinityflattens completely.- Only real arrays (
Array.isArray) are flattened. Array-like objects, strings and objects withSymbol.isConcatSpreadableare kept as single elements. - Holes are removed at every level that is being flattened, including the top level.
- Return a new array. Do not mutate
thisor any nested array. - Do not use the native
flat,flatMaporconcat.
Follow-up
- Write an iterative version that cannot overflow the call stack.
- Implement
flatMapon top of your helper. Why doesflatMaponly flatten one level?
Spotted a mistake or a rights concern? Report an issue