filter.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. * @static
  11. * @memberOf _
  12. * @since 0.1.0
  13. * @category Collection
  14. * @param {Array|Object} collection The collection to iterate over.
  15. * @param {Array|Function|Object|string} [predicate=_.identity]
  16. * The function invoked per iteration.
  17. * @returns {Array} Returns the new filtered array.
  18. * @see _.reject
  19. * @example
  20. *
  21. * var users = [
  22. * { 'user': 'barney', 'age': 36, 'active': true },
  23. * { 'user': 'fred', 'age': 40, 'active': false }
  24. * ];
  25. *
  26. * _.filter(users, function(o) { return !o.active; });
  27. * // => objects for ['fred']
  28. *
  29. * // The `_.matches` iteratee shorthand.
  30. * _.filter(users, { 'age': 36, 'active': true });
  31. * // => objects for ['barney']
  32. *
  33. * // The `_.matchesProperty` iteratee shorthand.
  34. * _.filter(users, ['active', false]);
  35. * // => objects for ['fred']
  36. *
  37. * // The `_.property` iteratee shorthand.
  38. * _.filter(users, 'active');
  39. * // => objects for ['barney']
  40. */
  41. function filter(collection, predicate) {
  42. var func = isArray(collection) ? arrayFilter : baseFilter;
  43. return func(collection, baseIteratee(predicate, 3));
  44. }
  45. module.exports = filter;