Skip to the solution
MediumDSA6 min read

Implement _.compact — remove falsy values

848 views

The problem

Problem, as an interviewer would state it: "Implement compact(array) — removing every FALSY value from the array, matching lodash's own well-known _.compact behavior."

Examples:

Code
compact([0, 1, false, 2, "", 3]); // [1, 2, 3]

Clarifying questions expected:

  • What is the real, complete, correct definition of "falsy" in JavaScript — every value that would evaluate as false in a boolean context?
  • Does this need to preserve the relative order of the surviving truthy elements?
  • Is this genuinely just a one-line filter, or is there a deeper real correctness concern worth discussing?

Code / implementation expected: Yes — real, direct proof against an array containing EVERY genuine JavaScript falsy value, confirming all are correctly removed while truthy order is preserved.

  • array
  • compact
  • falsy

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: compact() correctly removes every one of JavaScript's six real falsy values, verified against a single array containing all of them at once

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 100 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

Implement a Minimal useState Hook Using Closures (How React's State Actually Persists Between Renders)

Continue