find.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var baseEach = require('../internal/baseEach'),
  2. createFind = require('../internal/createFind');
  3. /**
  4. * Iterates over elements of `collection`, returning the first element
  5. * `predicate` returns truthy for. The predicate is bound to `thisArg` and
  6. * invoked with three arguments: (value, index|key, collection).
  7. *
  8. * If a property name is provided for `predicate` the created `_.property`
  9. * style callback returns the property value of the given element.
  10. *
  11. * If a value is also provided for `thisArg` the created `_.matchesProperty`
  12. * style callback returns `true` for elements that have a matching property
  13. * value, else `false`.
  14. *
  15. * If an object is provided for `predicate` the created `_.matches` style
  16. * callback returns `true` for elements that have the properties of the given
  17. * object, else `false`.
  18. *
  19. * @static
  20. * @memberOf _
  21. * @alias detect
  22. * @category Collection
  23. * @param {Array|Object|string} collection The collection to search.
  24. * @param {Function|Object|string} [predicate=_.identity] The function invoked
  25. * per iteration.
  26. * @param {*} [thisArg] The `this` binding of `predicate`.
  27. * @returns {*} Returns the matched element, else `undefined`.
  28. * @example
  29. *
  30. * var users = [
  31. * { 'user': 'barney', 'age': 36, 'active': true },
  32. * { 'user': 'fred', 'age': 40, 'active': false },
  33. * { 'user': 'pebbles', 'age': 1, 'active': true }
  34. * ];
  35. *
  36. * _.result(_.find(users, function(chr) {
  37. * return chr.age < 40;
  38. * }), 'user');
  39. * // => 'barney'
  40. *
  41. * // using the `_.matches` callback shorthand
  42. * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
  43. * // => 'pebbles'
  44. *
  45. * // using the `_.matchesProperty` callback shorthand
  46. * _.result(_.find(users, 'active', false), 'user');
  47. * // => 'fred'
  48. *
  49. * // using the `_.property` callback shorthand
  50. * _.result(_.find(users, 'active'), 'user');
  51. * // => 'barney'
  52. */
  53. var find = createFind(baseEach);
  54. module.exports = find;