Utility functions · mid
Flatten arrays and objects (and unflatten)
Flattening an array removes nesting up to a depth (with recursion or an explicit stack), and flattening an object turns nested keys into dot paths like { 'a.b': 1 } — with clear rules for arrays, empty objects and the prefix.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- flat(arr, depth = 1): for each item, if Array.isArray(item) and depth > 0, recurse with depth - 1; otherwise push it.
- Iterative version: a stack of [item, depth] pairs, for very deep input.
- Native: arr.flat(Infinity).
- Object flatten: recurse with a prefix; key = prefix ? prefix + '.' + k : k. Decide how arrays look ('a.0.b' or 'a[0].b') and what to do with empty objects. null is a leaf (typeof null is 'object').
- Unflatten: split each path and build nested objects, using arrays for numeric segments.
- Uses: form libraries (field paths), translation keys, analytics properties, query strings.
The red pen
Common traps: mistake → fix
Mistake: An empty prefix producing '.a'.
Mistake: Treating null as an object to recurse into.
Mistake: Mutating the input.
Easy to hard
Questions interviewers ask, easy to hard
- Implement flatten(arr, depth) without Array.prototype.flat. (Rippling, Salesforce)
- Write an iterative version.
- Flatten a nested object into dot-path keys. (Zepto)
- Write unflatten.
- How should arrays inside objects be named: a.0.b or a[0].b?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.