filter.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. function filter(collection, predicate) {
  43. var func = isArray(collection) ? arrayFilter : baseFilter;
  44. return func(collection, baseIteratee(predicate, 3));
  45. }
  46. module.exports = filter;