JS Built-ins
← Array66 / 226
ArrayArray.prototype.filterintermediate

Array.prototype.filter() β€” remove falsy values

πŸ“– Usage Example
const mixed = [0, 1, '', 'hello', null, true]
mixed.filter(Boolean)  // β†’ [1, 'hello', true]

Pass Boolean as the callback to filter() to remove all falsy values in one step.

Array.prototype.filter() β€” compact

A common utility pattern is to remove all falsy values (false, null, undefined, 0, "", NaN) from an array by passing Boolean as the filter callback.

Challenge: Implement compact(arr) that removes all falsy values from the array.

compact([0, 1, false, 2, '', 3, null]) // β†’ [1, 2, 3]
compact([null, undefined, NaN])        // β†’ []
πŸ’‘ Hints (2)
  • β€’ `Boolean` as a callback is equivalent to `x => !!x` β€” it converts each element to boolean.
  • β€’ Falsy values in JS: `false`, `0`, `""`, `null`, `undefined`, `NaN`.