Skip to the page

Frontend-flavoured problems · core

Flatten nested arrays and objects

Flattening walks a nested structure and emits leaves, with recursion or an explicit stack, and the senior details are the depth limit, holes, key paths for objects, and what to do with empty arrays, objects and cycles.

The notes

What you must know

  • Array.prototype.flat(depth = 1) removes holes and flattens up to depth levels; flat(Infinity) flattens fully.
  • Recursive flat: for each item, if Array.isArray(item) && depth > 0, recurse with depth − 1; else push.
  • Iterative flat (no recursion limit): a stack of [value, depth] pairs, or repeatedly concat; preserve order by pushing reversed or using an index.
  • Flatten object to paths: { a: { b: 1 } } → { 'a.b': 1 }; arrays become index keys ('d.0'). Decide and say what happens to empty objects/arrays, null, Dates.
  • Unflatten: split each key by '.', create objects along the path; mention keys that contain dots and how to escape them.
  • Cycles: track visited objects in a WeakSet and throw or skip.
  • Frontend uses: form field paths ('address.city'), i18n keys, analytics properties, query strings.

The red pen

Common traps: mistake → fix

  • Mistake: typeof x === 'object' means plain object

    Fix: null and arrays are 'object' too.

  • Mistake: Recursion is fine for any input

    Fix: deeply nested data can overflow; offer the stack version.

  • Mistake: flat() keeps holes

    Fix: it removes empty slots.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement flat(arr, depth).
  2. Now without recursion.
  3. Flatten a nested object into dot paths. What about arrays and empty objects?
  4. Unflatten it back. What if a key contains a dot?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview