filter.js
 1  var arrayFilter = require('./_arrayFilter'),
 2      baseFilter = require('./_baseFilter'),
 3      baseIteratee = require('./_baseIteratee'),
 4      isArray = require('./isArray');
 5  
 6  /**
 7   * Iterates over elements of `collection`, returning an array of all elements
 8   * `predicate` returns truthy for. The predicate is invoked with three
 9   * arguments: (value, index|key, collection).
10   *
11   * **Note:** Unlike `_.remove`, this method returns a new array.
12   *
13   * @static
14   * @memberOf _
15   * @since 0.1.0
16   * @category Collection
17   * @param {Array|Object} collection The collection to iterate over.
18   * @param {Function} [predicate=_.identity] The function invoked per iteration.
19   * @returns {Array} Returns the new filtered array.
20   * @see _.reject
21   * @example
22   *
23   * var users = [
24   *   { 'user': 'barney', 'age': 36, 'active': true },
25   *   { 'user': 'fred',   'age': 40, 'active': false }
26   * ];
27   *
28   * _.filter(users, function(o) { return !o.active; });
29   * // => objects for ['fred']
30   *
31   * // The `_.matches` iteratee shorthand.
32   * _.filter(users, { 'age': 36, 'active': true });
33   * // => objects for ['barney']
34   *
35   * // The `_.matchesProperty` iteratee shorthand.
36   * _.filter(users, ['active', false]);
37   * // => objects for ['fred']
38   *
39   * // The `_.property` iteratee shorthand.
40   * _.filter(users, 'active');
41   * // => objects for ['barney']
42   *
43   * // Combining several predicates using `_.overEvery` or `_.overSome`.
44   * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
45   * // => objects for ['fred', 'barney']
46   */
47  function filter(collection, predicate) {
48    var func = isArray(collection) ? arrayFilter : baseFilter;
49    return func(collection, baseIteratee(predicate, 3));
50  }
51  
52  module.exports = filter;