Skip to the solution
MediumDSAAsked in 20246 min read

Clear Nullish Values

3.4k views

The problem

Problem, as an interviewer would state it: "Implement clearNullish(value) — recursively removing every null and undefined from an object or array, without touching other falsy values, without mutating the input, and without crashing on a circular reference."

Examples:

Code
clearNullish({ a: 1, b: null, c: { d: undefined, e: 0 } });
// { a: 1, c: { e: 0 } }

Clarifying questions expected:

  • Should 0, "" and false survive? (They are falsy but not nullish.)
  • For arrays, should nullish elements be removed and the rest shifted down, or should surviving elements keep their original indices?
  • What should happen with a circular reference, and with non-plain objects such as a Date?

Code / implementation expected: Yes — real, direct proof on nested data, on a circular structure, and in both array modes.

  • object
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: nullish values are removed recursively, other falsy values survive, a cycle is preserved, and arrays support compact and index-preserving modes

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 56 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Throttle async promise resolver

Continue