compact

JavaScript, Array

Removes falsy values from an array.

  • Use Array.prototype.filter() to filter out falsy values (false, null, 0, "", undefined, and NaN).
const compact = arr => arr.filter(Boolean);
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 
// [ 1, 2, 3, 'a', 's', 34 ]

Recommended snippets & collections

  • JavaScript Array Tricks

    Snippet collection

    Learn a handful of awesome tips and tricks that you can leverage in your code to make array manipulation a breeze.

  • compactObject

    JavaScript, Object

    Deeply removes all falsy values from an object or array.

  • pullAtIndex

    JavaScript, Array

    Mutates the original array to filter out the values at the specified indexes. Returns the removed elements.

  • pullAtValue

    JavaScript, Array

    Mutates the original array to filter out the values specified. Returns the removed elements.