Skip to the page

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.

The 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

  1. Implement flatten(arr, depth) without Array.prototype.flat. (Rippling, Salesforce)
  2. Write an iterative version.
  3. Flatten a nested object into dot-path keys. (Zepto)
  4. Write unflatten.
  5. How should arrays inside objects be named: a.0.b or a[0].b?

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