Compact Array

EasyUtility Functions5 min4 tests

Implement a compact function that removes all falsy values from an array.

Requirements

  • Remove false, null, 0, "", undefined, and NaN
  • Return a new array (do not mutate the original)
  • Preserve the order of remaining elements

Example

compact([0, 1, false, 2, '', 3, null]); // [1, 2, 3]
compact([null, undefined, NaN, 'hello']); // ['hello']
Hints (3)
  1. Falsy values in JavaScript are: false, null, 0, "", undefined, and NaN.
  2. The Boolean function can be used as a filter callback.
  3. Array.prototype.filter creates a new array, so the original is not mutated.

Topics

  • Utility Functions

Asked at

Google · Amazon · Microsoft

Join Us
blur