Design & Download
Your JS Library
in Seconds!!!

Snippet: compact() - An Array or Object Without Falsy Values

Written by Christopher West (cwest) on December 19, 2015.
Creates a copy of an array (or an array-like object) or an object without falsy values.
function compact(arrOrObj, opt_filterOutNothings) {
  return filter(arrOrObj, function(value) {
    return opt_filterOutNothings ? !isNothing(value) : value;
  });
}

compact(...) API Documentation

Description

Creates a copy of an array (or an array-like object) or an object without falsy values.

Parameters

  1. arrOrObj {Array|Object}:
    If this is an array or array-like it will be traversed like an array otherwise it will be traversed like an object. opt_filterOutNothings {boolean=}:
    Optional. Defaults to false. Ordinarilly falsy values will not include empty arrays and empty objects but if this is true both empty arrays and empty objects will be considered falsy and will be excluded in the returned array or object.

Returns

If arrOrObj is an array or is an array-like object an array of the objects that were not falsy will be returned. If arrOrObj is not array-like, an object will be returned that only contains the non-falsy values.