Write your own function to flatten a nested array.
Difficulty: 3/10
recursion, array handling, performance
javascript
Scenario Questions
0-2 years experience
1How would you write a function that takes an array which may contain nested arrays and returns a new flat array with all values on a single level?
2If you call your flatten function on [1, [2, [3, 4]], 5], what should the result be and why?
3What would happen if the input contains non‑array values like null or objects, and how would you handle that?
2-5 years experience
1We need to flatten user‑provided JSON data before storing it; the data can be deeply nested and may include objects. How would you adapt your flatten function to ignore non‑array elements and preserve order?
2During a code review you notice the flatten implementation is causing a stack overflow on very deep arrays. How would you refactor it to avoid this issue?
3Our front‑end receives a mixed array of numbers and strings, some nested. The team wants the flatten function to also concatenate string elements into a single comma‑separated string. How would you modify your solution?
5-8 years experience
1Our service processes millions of records per second and uses a flatten step on each payload. Discuss the performance implications of a recursive vs iterative flatten implementation and which you would choose.
2We have a microservice that receives arbitrarily nested arrays from external partners. How would you design a robust flatten utility that validates input, handles circular references, and fails gracefully?
3If the flatten operation becomes a bottleneck, what caching or streaming strategies could you employ to reduce latency while preserving correctness?
8+ years experience
1Our platform is moving from a monolithic Node.js codebase to a distributed system with multiple languages. How would you abstract the flatten functionality so it can be reused across services written in JavaScript, TypeScript, and maybe Go, while ensuring consistent behavior?
2We need to deprecate an old flatten helper that mutates the original array. Describe a migration plan to replace it with an immutable version across all repositories, considering testing, versioning, and backward compatibility.
3When designing a data ingestion pipeline that normalizes nested arrays into a relational schema, what considerations would you make about flattening at the edge versus downstream, and how would that affect schema evolution?
Follow-up Questions
How would you modify the function to skip non‑array values like objects or null?
What trade‑offs exist between a recursive and an iterative implementation in terms of memory usage?
If the input could contain circular references, how would you protect against infinite loops?
Sharethis question
Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.