filter.js 1.6 KB

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