Compact array

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 ]

More like this

  • JavaScript Array Tricks

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

    Collection · 12 snippets

  • Compact and join array

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

    JavaScript, Array · Apr 8, 2022

  • Compact object

    Deeply removes all falsy values from an object or array.

    JavaScript, Object · Nov 27, 2020

  • Pull values from array at index

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

    JavaScript, Array · Oct 22, 2020