where.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. var baseMatches = require('../internal/baseMatches'),
  2. filter = require('./filter');
  3. /**
  4. * Performs a deep comparison between each element in `collection` and the
  5. * source object, returning an array of all elements that have equivalent
  6. * property values.
  7. *
  8. * **Note:** This method supports comparing arrays, booleans, `Date` objects,
  9. * numbers, `Object` objects, regexes, and strings. Objects are compared by
  10. * their own, not inherited, enumerable properties. For comparing a single
  11. * own or inherited property value see `_.matchesProperty`.
  12. *
  13. * @static
  14. * @memberOf _
  15. * @category Collection
  16. * @param {Array|Object|string} collection The collection to search.
  17. * @param {Object} source The object of property values to match.
  18. * @returns {Array} Returns the new filtered array.
  19. * @example
  20. *
  21. * var users = [
  22. * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
  23. * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
  24. * ];
  25. *
  26. * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
  27. * // => ['barney']
  28. *
  29. * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
  30. * // => ['fred']
  31. */
  32. function where(collection, source) {
  33. return filter(collection, baseMatches(source));
  34. }
  35. module.exports = where;