Design & Download
Your JS Library
in Seconds!!!

Snippet: filter() - Keep Specific Values

Written by Christopher West (cwest) on November 29, 2015.
Creates a new version of an array (or an array-like object) or a object with only the desired values included.
function filter(arrOrObj, fnFilter, opt_filterOut) {
  opt_filterOut = !opt_filterOut;
  fnFilter = getSimpleCallback(fnFilter);
  var me = this, returnsArray = isArrayLike(arrOrObj);
  return reduce(arrOrObj, function(ret, value, key) {
    if (opt_filterOut != !fnFilter.call(me, value, key, arrOrObj)) {
      if (returnsArray) {
        ret.push(value);
      }
      else {
        ret[key] = value;
      }
    }
    return ret;
  }, returnsArray ? [] : {});
}

As of ES5, Array.prototype.filter() became available to most modern browsers. Unfortunately the older browsers and environments don't have this function defined but there are polyfills. The nice thing about this YourJS snippet is that it defines a similar function which can also be used on array-like objects and normal objects.

filter() API Documentation

Description

Creates a new version of an array (or an array-like object) or a object with only the desired values included.

Parameters

  1. arrOrObj {Array|Object}:
    The array or object to be copied and filtered.
  2. fnFilter {function(value,key,arrOrObj)}:
    Function used to filter out keys/values. The function will act as an iterator for all of the values in an array/object and will be passed the value, key, and arrOrObj as the 3 parameters. If a true-ish value is returned, that key/value pair will be kept in the copy arrOrObj passed back from YourJS.filter(). If a false-ish value is returned, that key/value pair will be excluded from the copy of arrOrObj passed back from YourJS.filter().
  3. opt_filterOut {Boolean}:
    Optional. Defaults to false. If true, the values returned will only be those for which fnFilter() returns a false-ish value.

Returns

Returns a shallow-copy of arrOrObj with only the desired keys (or indices) as indicated by fnFilter().