CompactLoading saved progress…

Compact

Arrays you build from real-world data — form fields, parsed query strings, joined query results — often end up sprinkled with null, undefined, empty strings, and the occasional NaN. Before you render or process the list, you want the gaps gone.

Implement compact(array), which returns a new array with every falsy value removed. This mirrors lodash's _.compact and is a common one-line interview warm-up that hides a subtle gotcha around the string "0".

Signature

function compact(array) {
  // returns a new array containing only the truthy values from `array`,
  // in their original order
}

Examples

compact([0, 1, false, 2, '', 3, null]);
// → [1, 2, 3]

compact(['hello', undefined, 'world', NaN, 0n, 'js']);
// → ['hello', 'world', 'js']

Notes

  • Falsy values in JavaScript are false, null, undefined, 0, NaN, "", and 0n — these all get stripped.
  • String "0" stays — it's a non-empty string, which is truthy. Only the number 0 is falsy.
  • Return a new array — do not mutate the input.
  • Preserve order — the surviving items keep their original positions relative to each other.
  • Empty inputcompact([]) returns [].
  • Don't worry about nested arrays or deep traversal — operate only on the top level.
Loading editor…