partition.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var createAggregator = require('../internal/createAggregator');
  2. /**
  3. * Creates an array of elements split into two groups, the first of which
  4. * contains elements `predicate` returns truthy for, while the second of which
  5. * contains elements `predicate` returns falsey for. The predicate is bound
  6. * to `thisArg` and 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. * @category Collection
  22. * @param {Array|Object|string} collection The collection to iterate over.
  23. * @param {Function|Object|string} [predicate=_.identity] The function invoked
  24. * per iteration.
  25. * @param {*} [thisArg] The `this` binding of `predicate`.
  26. * @returns {Array} Returns the array of grouped elements.
  27. * @example
  28. *
  29. * _.partition([1, 2, 3], function(n) {
  30. * return n % 2;
  31. * });
  32. * // => [[1, 3], [2]]
  33. *
  34. * _.partition([1.2, 2.3, 3.4], function(n) {
  35. * return this.floor(n) % 2;
  36. * }, Math);
  37. * // => [[1.2, 3.4], [2.3]]
  38. *
  39. * var users = [
  40. * { 'user': 'barney', 'age': 36, 'active': false },
  41. * { 'user': 'fred', 'age': 40, 'active': true },
  42. * { 'user': 'pebbles', 'age': 1, 'active': false }
  43. * ];
  44. *
  45. * var mapper = function(array) {
  46. * return _.pluck(array, 'user');
  47. * };
  48. *
  49. * // using the `_.matches` callback shorthand
  50. * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
  51. * // => [['pebbles'], ['barney', 'fred']]
  52. *
  53. * // using the `_.matchesProperty` callback shorthand
  54. * _.map(_.partition(users, 'active', false), mapper);
  55. * // => [['barney', 'pebbles'], ['fred']]
  56. *
  57. * // using the `_.property` callback shorthand
  58. * _.map(_.partition(users, 'active'), mapper);
  59. * // => [['fred'], ['barney', 'pebbles']]
  60. */
  61. var partition = createAggregator(function(result, value, key) {
  62. result[key ? 0 : 1].push(value);
  63. }, function() { return [[], []]; });
  64. module.exports = partition;