Compact array

OSCC · JavaScript, Array · Oct 22, 2020

Removes falsy values from an array.

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.

  • Compact and join array

    JavaScript, Array

    Removes falsy values from an array and combines the remaining values into a string.

  • Compact object

    JavaScript, Object

    Deeply removes all falsy values from an object or array.

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