partition.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var createAggregator = require('./_createAggregator');
  2. /**
  3. * Creates an array of elements split into two groups, the first of which
  4. * contains elements `predicate` returns truthy for, the second of which
  5. * contains elements `predicate` returns falsey for. The predicate is
  6. * invoked with one argument: (value).
  7. *
  8. * @static
  9. * @memberOf _
  10. * @since 3.0.0
  11. * @category Collection
  12. * @param {Array|Object} collection The collection to iterate over.
  13. * @param {Array|Function|Object|string} [predicate=_.identity]
  14. * The function invoked per iteration.
  15. * @returns {Array} Returns the array of grouped elements.
  16. * @example
  17. *
  18. * var users = [
  19. * { 'user': 'barney', 'age': 36, 'active': false },
  20. * { 'user': 'fred', 'age': 40, 'active': true },
  21. * { 'user': 'pebbles', 'age': 1, 'active': false }
  22. * ];
  23. *
  24. * _.partition(users, function(o) { return o.active; });
  25. * // => objects for [['fred'], ['barney', 'pebbles']]
  26. *
  27. * // The `_.matches` iteratee shorthand.
  28. * _.partition(users, { 'age': 1, 'active': false });
  29. * // => objects for [['pebbles'], ['barney', 'fred']]
  30. *
  31. * // The `_.matchesProperty` iteratee shorthand.
  32. * _.partition(users, ['active', false]);
  33. * // => objects for [['barney', 'pebbles'], ['fred']]
  34. *
  35. * // The `_.property` iteratee shorthand.
  36. * _.partition(users, 'active');
  37. * // => objects for [['fred'], ['barney', 'pebbles']]
  38. */
  39. var partition = createAggregator(function(result, value, key) {
  40. result[key ? 0 : 1].push(value);
  41. }, function() { return [[], []]; });
  42. module.exports = partition;