Flatten to a depth
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Flatten the nested arrays in `arr` by `depth` levels, the way `Array.prototype.flat(depth)` does, but written by hand. `depth` 1 removes one level of nesting, `depth` 0 returns a shallow copy, and `depth` can be `Infinity` to flatten everything. An empty array within the depth contributes nothing; an array beyond the depth (including an empty one) stays as an item. `null` and `undefined` are ordinary items. Do not change `arr`.
What this exercise teaches
Recursion that passes depth - 1 down stops exactly where it should, and works for Infinity because Infinity - 1 is still Infinity. A loop that flattens one level depth times never ends for Infinity, and concat spreads arrays one level deeper than you asked.
A hint if you get stuck
Write it recursively: for each item, if it is an array and `depth > 0`, push the items of `flattenDepth(item, depth - 1)`; otherwise push the item itself. `Array.isArray` tells arrays from everything else.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Arrays and objects
- Group by a fieldFree
- Count by a fieldFree
- Remove duplicates by a fieldFree
- Split into chunksFree
- Zip two arraysFree
- Flatten one levelFree
- Pick some keysFree
- Sort by several keysFree
- Merge settingsFree
- Omit some keysFree
- Transpose a matrixFree
- Binary searchFree
- Two numbers that add upFree
- Values in both arraysFree
- Rotate an arrayFree